blob: 0b612470d24bf1eaff323980f48b7c7bc1e20431 [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.
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00003272 final List<Network> underlying = (List<Network>) arg.second;
3273
3274 if (isLegacyLockdownNai(nai)
3275 && (underlying == null || underlying.size() != 1)) {
3276 Log.wtf(TAG, "Legacy lockdown VPN " + nai.toShortString()
3277 + " must have exactly one underlying network: " + underlying);
3278 }
3279
3280 final Network[] oldUnderlying = nai.declaredUnderlyingNetworks;
3281 nai.declaredUnderlyingNetworks = (underlying != null)
3282 ? underlying.toArray(new Network[0]) : null;
3283
3284 if (!Arrays.equals(oldUnderlying, nai.declaredUnderlyingNetworks)) {
3285 if (DBG) {
3286 log(nai.toShortString() + " changed underlying networks to "
3287 + Arrays.toString(nai.declaredUnderlyingNetworks));
3288 }
3289 updateCapabilitiesForNetwork(nai);
3290 notifyIfacesChangedForNetworkStats();
3291 }
3292 break;
3293 }
3294 case NetworkAgent.EVENT_TEARDOWN_DELAY_CHANGED: {
3295 if (msg.arg1 >= 0 && msg.arg1 <= NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
3296 nai.teardownDelayMs = msg.arg1;
3297 } else {
3298 logwtf(nai.toShortString() + " set invalid teardown delay " + msg.arg1);
3299 }
3300 break;
3301 }
3302 case NetworkAgent.EVENT_LINGER_DURATION_CHANGED: {
3303 nai.setLingerDuration((int) arg.second);
3304 break;
3305 }
3306 }
3307 }
3308
3309 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
3310 switch (msg.what) {
3311 default:
3312 return false;
3313 case EVENT_PROBE_STATUS_CHANGED: {
3314 final Integer netId = (Integer) msg.obj;
3315 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
3316 if (nai == null) {
3317 break;
3318 }
3319 final boolean probePrivateDnsCompleted =
3320 ((msg.arg1 & NETWORK_VALIDATION_PROBE_PRIVDNS) != 0);
3321 final boolean privateDnsBroken =
3322 ((msg.arg2 & NETWORK_VALIDATION_PROBE_PRIVDNS) == 0);
3323 if (probePrivateDnsCompleted) {
3324 if (nai.networkCapabilities.isPrivateDnsBroken() != privateDnsBroken) {
3325 nai.networkCapabilities.setPrivateDnsBroken(privateDnsBroken);
3326 updateCapabilitiesForNetwork(nai);
3327 }
3328 // Only show the notification when the private DNS is broken and the
3329 // PRIVATE_DNS_BROKEN notification hasn't shown since last valid.
3330 if (privateDnsBroken && !nai.networkAgentConfig.hasShownBroken) {
3331 showNetworkNotification(nai, NotificationType.PRIVATE_DNS_BROKEN);
3332 }
3333 nai.networkAgentConfig.hasShownBroken = privateDnsBroken;
3334 } else if (nai.networkCapabilities.isPrivateDnsBroken()) {
3335 // If probePrivateDnsCompleted is false but nai.networkCapabilities says
3336 // private DNS is broken, it means this network is being reevaluated.
3337 // Either probing private DNS is not necessary any more or it hasn't been
3338 // done yet. In either case, the networkCapabilities should be updated to
3339 // reflect the new status.
3340 nai.networkCapabilities.setPrivateDnsBroken(false);
3341 updateCapabilitiesForNetwork(nai);
3342 nai.networkAgentConfig.hasShownBroken = false;
3343 }
3344 break;
3345 }
3346 case EVENT_NETWORK_TESTED: {
3347 final NetworkTestedResults results = (NetworkTestedResults) msg.obj;
3348
3349 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(results.mNetId);
3350 if (nai == null) break;
3351
3352 handleNetworkTested(nai, results.mTestResult,
3353 (results.mRedirectUrl == null) ? "" : results.mRedirectUrl);
3354 break;
3355 }
3356 case EVENT_PROVISIONING_NOTIFICATION: {
3357 final int netId = msg.arg2;
3358 final boolean visible = toBool(msg.arg1);
3359 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
3360 // If captive portal status has changed, update capabilities or disconnect.
3361 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
3362 nai.lastCaptivePortalDetected = visible;
3363 nai.everCaptivePortalDetected |= visible;
3364 if (nai.lastCaptivePortalDetected &&
3365 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_AVOID
3366 == getCaptivePortalMode()) {
3367 if (DBG) log("Avoiding captive portal network: " + nai.toShortString());
3368 nai.onPreventAutomaticReconnect();
3369 teardownUnneededNetwork(nai);
3370 break;
3371 }
3372 updateCapabilitiesForNetwork(nai);
3373 }
3374 if (!visible) {
3375 // Only clear SIGN_IN and NETWORK_SWITCH notifications here, or else other
3376 // notifications belong to the same network may be cleared unexpectedly.
3377 mNotifier.clearNotification(netId, NotificationType.SIGN_IN);
3378 mNotifier.clearNotification(netId, NotificationType.NETWORK_SWITCH);
3379 } else {
3380 if (nai == null) {
3381 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
3382 break;
3383 }
3384 if (!nai.networkAgentConfig.provisioningNotificationDisabled) {
3385 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
3386 (PendingIntent) msg.obj,
3387 nai.networkAgentConfig.explicitlySelected);
3388 }
3389 }
3390 break;
3391 }
3392 case EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
3393 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
3394 if (nai == null) break;
3395
3396 updatePrivateDns(nai, (PrivateDnsConfig) msg.obj);
3397 break;
3398 }
3399 case EVENT_CAPPORT_DATA_CHANGED: {
3400 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
3401 if (nai == null) break;
3402 handleCapportApiDataUpdate(nai, (CaptivePortalData) msg.obj);
3403 break;
3404 }
3405 }
3406 return true;
3407 }
3408
3409 private void handleNetworkTested(
3410 @NonNull NetworkAgentInfo nai, int testResult, @NonNull String redirectUrl) {
3411 final boolean wasPartial = nai.partialConnectivity;
3412 nai.partialConnectivity = ((testResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0);
3413 final boolean partialConnectivityChanged =
3414 (wasPartial != nai.partialConnectivity);
3415
3416 final boolean valid = ((testResult & NETWORK_VALIDATION_RESULT_VALID) != 0);
3417 final boolean wasValidated = nai.lastValidated;
3418 final boolean wasDefault = isDefaultNetwork(nai);
3419
3420 if (DBG) {
3421 final String logMsg = !TextUtils.isEmpty(redirectUrl)
3422 ? " with redirect to " + redirectUrl
3423 : "";
3424 log(nai.toShortString() + " validation " + (valid ? "passed" : "failed") + logMsg);
3425 }
3426 if (valid != nai.lastValidated) {
3427 final int oldScore = nai.getCurrentScore();
3428 nai.lastValidated = valid;
3429 nai.everValidated |= valid;
3430 updateCapabilities(oldScore, nai, nai.networkCapabilities);
3431 if (valid) {
3432 handleFreshlyValidatedNetwork(nai);
3433 // Clear NO_INTERNET, PRIVATE_DNS_BROKEN, PARTIAL_CONNECTIVITY and
3434 // LOST_INTERNET notifications if network becomes valid.
3435 mNotifier.clearNotification(nai.network.getNetId(),
3436 NotificationType.NO_INTERNET);
3437 mNotifier.clearNotification(nai.network.getNetId(),
3438 NotificationType.LOST_INTERNET);
3439 mNotifier.clearNotification(nai.network.getNetId(),
3440 NotificationType.PARTIAL_CONNECTIVITY);
3441 mNotifier.clearNotification(nai.network.getNetId(),
3442 NotificationType.PRIVATE_DNS_BROKEN);
3443 // If network becomes valid, the hasShownBroken should be reset for
3444 // that network so that the notification will be fired when the private
3445 // DNS is broken again.
3446 nai.networkAgentConfig.hasShownBroken = false;
3447 }
3448 } else if (partialConnectivityChanged) {
3449 updateCapabilitiesForNetwork(nai);
3450 }
3451 updateInetCondition(nai);
3452 // Let the NetworkAgent know the state of its network
3453 // TODO: Evaluate to update partial connectivity to status to NetworkAgent.
3454 nai.onValidationStatusChanged(
3455 valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK,
3456 redirectUrl);
3457
3458 // If NetworkMonitor detects partial connectivity before
3459 // EVENT_PROMPT_UNVALIDATED arrives, show the partial connectivity notification
3460 // immediately. Re-notify partial connectivity silently if no internet
3461 // notification already there.
3462 if (!wasPartial && nai.partialConnectivity) {
3463 // Remove delayed message if there is a pending message.
3464 mHandler.removeMessages(EVENT_PROMPT_UNVALIDATED, nai.network);
3465 handlePromptUnvalidated(nai.network);
3466 }
3467
3468 if (wasValidated && !nai.lastValidated) {
3469 handleNetworkUnvalidated(nai);
3470 }
3471 }
3472
3473 private int getCaptivePortalMode() {
3474 return Settings.Global.getInt(mContext.getContentResolver(),
3475 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE,
3476 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_PROMPT);
3477 }
3478
3479 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
3480 switch (msg.what) {
3481 default:
3482 return false;
3483 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
3484 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
3485 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
3486 handleLingerComplete(nai);
3487 }
3488 break;
3489 }
3490 case NetworkAgentInfo.EVENT_AGENT_REGISTERED: {
3491 handleNetworkAgentRegistered(msg);
3492 break;
3493 }
3494 case NetworkAgentInfo.EVENT_AGENT_DISCONNECTED: {
3495 handleNetworkAgentDisconnected(msg);
3496 break;
3497 }
3498 }
3499 return true;
3500 }
3501
3502 @Override
3503 public void handleMessage(Message msg) {
3504 if (!maybeHandleNetworkMonitorMessage(msg)
3505 && !maybeHandleNetworkAgentInfoMessage(msg)) {
3506 maybeHandleNetworkAgentMessage(msg);
3507 }
3508 }
3509 }
3510
3511 private class NetworkMonitorCallbacks extends INetworkMonitorCallbacks.Stub {
3512 private final int mNetId;
3513 private final AutodestructReference<NetworkAgentInfo> mNai;
3514
3515 private NetworkMonitorCallbacks(NetworkAgentInfo nai) {
3516 mNetId = nai.network.getNetId();
3517 mNai = new AutodestructReference<>(nai);
3518 }
3519
3520 @Override
3521 public void onNetworkMonitorCreated(INetworkMonitor networkMonitor) {
3522 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT,
3523 new Pair<>(mNai.getAndDestroy(), networkMonitor)));
3524 }
3525
3526 @Override
3527 public void notifyNetworkTested(int testResult, @Nullable String redirectUrl) {
3528 // Legacy version of notifyNetworkTestedWithExtras.
3529 // Would only be called if the system has a NetworkStack module older than the
3530 // framework, which does not happen in practice.
3531 Log.wtf(TAG, "Deprecated notifyNetworkTested called: no action taken");
3532 }
3533
3534 @Override
3535 public void notifyNetworkTestedWithExtras(NetworkTestResultParcelable p) {
3536 // Notify mTrackerHandler and mConnectivityDiagnosticsHandler of the event. Both use
3537 // the same looper so messages will be processed in sequence.
3538 final Message msg = mTrackerHandler.obtainMessage(
3539 EVENT_NETWORK_TESTED,
3540 new NetworkTestedResults(
3541 mNetId, p.result, p.timestampMillis, p.redirectUrl));
3542 mTrackerHandler.sendMessage(msg);
3543
3544 // Invoke ConnectivityReport generation for this Network test event.
3545 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(mNetId);
3546 if (nai == null) return;
3547
3548 final PersistableBundle extras = new PersistableBundle();
3549 extras.putInt(KEY_NETWORK_VALIDATION_RESULT, p.result);
3550 extras.putInt(KEY_NETWORK_PROBES_SUCCEEDED_BITMASK, p.probesSucceeded);
3551 extras.putInt(KEY_NETWORK_PROBES_ATTEMPTED_BITMASK, p.probesAttempted);
3552
3553 ConnectivityReportEvent reportEvent =
3554 new ConnectivityReportEvent(p.timestampMillis, nai, extras);
3555 final Message m = mConnectivityDiagnosticsHandler.obtainMessage(
3556 ConnectivityDiagnosticsHandler.EVENT_NETWORK_TESTED, reportEvent);
3557 mConnectivityDiagnosticsHandler.sendMessage(m);
3558 }
3559
3560 @Override
3561 public void notifyPrivateDnsConfigResolved(PrivateDnsConfigParcel config) {
3562 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3563 EVENT_PRIVATE_DNS_CONFIG_RESOLVED,
3564 0, mNetId, PrivateDnsConfig.fromParcel(config)));
3565 }
3566
3567 @Override
3568 public void notifyProbeStatusChanged(int probesCompleted, int probesSucceeded) {
3569 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3570 EVENT_PROBE_STATUS_CHANGED,
3571 probesCompleted, probesSucceeded, new Integer(mNetId)));
3572 }
3573
3574 @Override
3575 public void notifyCaptivePortalDataChanged(CaptivePortalData data) {
3576 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3577 EVENT_CAPPORT_DATA_CHANGED,
3578 0, mNetId, data));
3579 }
3580
3581 @Override
3582 public void showProvisioningNotification(String action, String packageName) {
3583 final Intent intent = new Intent(action);
3584 intent.setPackage(packageName);
3585
3586 final PendingIntent pendingIntent;
3587 // Only the system server can register notifications with package "android"
3588 final long token = Binder.clearCallingIdentity();
3589 try {
3590 pendingIntent = PendingIntent.getBroadcast(
3591 mContext,
3592 0 /* requestCode */,
3593 intent,
3594 PendingIntent.FLAG_IMMUTABLE);
3595 } finally {
3596 Binder.restoreCallingIdentity(token);
3597 }
3598 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3599 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_SHOW,
3600 mNetId, pendingIntent));
3601 }
3602
3603 @Override
3604 public void hideProvisioningNotification() {
3605 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3606 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_HIDE, mNetId));
3607 }
3608
3609 @Override
3610 public void notifyDataStallSuspected(DataStallReportParcelable p) {
3611 ConnectivityService.this.notifyDataStallSuspected(p, mNetId);
3612 }
3613
3614 @Override
3615 public int getInterfaceVersion() {
3616 return this.VERSION;
3617 }
3618
3619 @Override
3620 public String getInterfaceHash() {
3621 return this.HASH;
3622 }
3623 }
3624
3625 private void notifyDataStallSuspected(DataStallReportParcelable p, int netId) {
3626 log("Data stall detected with methods: " + p.detectionMethod);
3627
3628 final PersistableBundle extras = new PersistableBundle();
3629 int detectionMethod = 0;
3630 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
3631 extras.putInt(KEY_DNS_CONSECUTIVE_TIMEOUTS, p.dnsConsecutiveTimeouts);
3632 detectionMethod |= DETECTION_METHOD_DNS_EVENTS;
3633 }
3634 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
3635 extras.putInt(KEY_TCP_PACKET_FAIL_RATE, p.tcpPacketFailRate);
3636 extras.putInt(KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS,
3637 p.tcpMetricsCollectionPeriodMillis);
3638 detectionMethod |= DETECTION_METHOD_TCP_METRICS;
3639 }
3640
3641 final Message msg = mConnectivityDiagnosticsHandler.obtainMessage(
3642 ConnectivityDiagnosticsHandler.EVENT_DATA_STALL_SUSPECTED, detectionMethod, netId,
3643 new Pair<>(p.timestampMillis, extras));
3644
3645 // NetworkStateTrackerHandler currently doesn't take any actions based on data
3646 // stalls so send the message directly to ConnectivityDiagnosticsHandler and avoid
3647 // the cost of going through two handlers.
3648 mConnectivityDiagnosticsHandler.sendMessage(msg);
3649 }
3650
3651 private boolean hasDataStallDetectionMethod(DataStallReportParcelable p, int detectionMethod) {
3652 return (p.detectionMethod & detectionMethod) != 0;
3653 }
3654
3655 private boolean networkRequiresPrivateDnsValidation(NetworkAgentInfo nai) {
3656 return isPrivateDnsValidationRequired(nai.networkCapabilities);
3657 }
3658
3659 private void handleFreshlyValidatedNetwork(NetworkAgentInfo nai) {
3660 if (nai == null) return;
3661 // If the Private DNS mode is opportunistic, reprogram the DNS servers
3662 // in order to restart a validation pass from within netd.
3663 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
3664 if (cfg.useTls && TextUtils.isEmpty(cfg.hostname)) {
3665 updateDnses(nai.linkProperties, null, nai.network.getNetId());
3666 }
3667 }
3668
3669 private void handlePrivateDnsSettingsChanged() {
3670 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
3671
3672 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
3673 handlePerNetworkPrivateDnsConfig(nai, cfg);
3674 if (networkRequiresPrivateDnsValidation(nai)) {
3675 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
3676 }
3677 }
3678 }
3679
3680 private void handlePerNetworkPrivateDnsConfig(NetworkAgentInfo nai, PrivateDnsConfig cfg) {
3681 // Private DNS only ever applies to networks that might provide
3682 // Internet access and therefore also require validation.
3683 if (!networkRequiresPrivateDnsValidation(nai)) return;
3684
3685 // Notify the NetworkAgentInfo/NetworkMonitor in case NetworkMonitor needs to cancel or
3686 // schedule DNS resolutions. If a DNS resolution is required the
3687 // result will be sent back to us.
3688 nai.networkMonitor().notifyPrivateDnsChanged(cfg.toParcel());
3689
3690 // With Private DNS bypass support, we can proceed to update the
3691 // Private DNS config immediately, even if we're in strict mode
3692 // and have not yet resolved the provider name into a set of IPs.
3693 updatePrivateDns(nai, cfg);
3694 }
3695
3696 private void updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
3697 mDnsManager.updatePrivateDns(nai.network, newCfg);
3698 updateDnses(nai.linkProperties, null, nai.network.getNetId());
3699 }
3700
3701 private void handlePrivateDnsValidationUpdate(PrivateDnsValidationUpdate update) {
3702 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(update.netId);
3703 if (nai == null) {
3704 return;
3705 }
3706 mDnsManager.updatePrivateDnsValidation(update);
3707 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
3708 }
3709
3710 private void handleNat64PrefixEvent(int netId, int operation, String prefixAddress,
3711 int prefixLength) {
3712 NetworkAgentInfo nai = mNetworkForNetId.get(netId);
3713 if (nai == null) return;
3714
3715 log(String.format("NAT64 prefix changed on netId %d: operation=%d, %s/%d",
3716 netId, operation, prefixAddress, prefixLength));
3717
3718 IpPrefix prefix = null;
3719 if (operation == IDnsResolverUnsolicitedEventListener.PREFIX_OPERATION_ADDED) {
3720 try {
3721 prefix = new IpPrefix(InetAddresses.parseNumericAddress(prefixAddress),
3722 prefixLength);
3723 } catch (IllegalArgumentException e) {
3724 loge("Invalid NAT64 prefix " + prefixAddress + "/" + prefixLength);
3725 return;
3726 }
3727 }
3728
3729 nai.clatd.setNat64PrefixFromDns(prefix);
3730 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
3731 }
3732
3733 private void handleCapportApiDataUpdate(@NonNull final NetworkAgentInfo nai,
3734 @Nullable final CaptivePortalData data) {
3735 nai.capportApiData = data;
3736 // CaptivePortalData will be merged into LinkProperties from NetworkAgentInfo
3737 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
3738 }
3739
3740 /**
3741 * Updates the inactivity state from the network requests inside the NAI.
3742 * @param nai the agent info to update
3743 * @param now the timestamp of the event causing this update
3744 * @return whether the network was inactive as a result of this update
3745 */
3746 private boolean updateInactivityState(@NonNull final NetworkAgentInfo nai, final long now) {
3747 // 1. Update the inactivity timer. If it's changed, reschedule or cancel the alarm.
3748 // 2. If the network was inactive and there are now requests, unset inactive.
3749 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
3750 // one lingered request, set inactive.
3751 nai.updateInactivityTimer();
3752 if (nai.isInactive() && nai.numForegroundNetworkRequests() > 0) {
3753 if (DBG) log("Unsetting inactive " + nai.toShortString());
3754 nai.unsetInactive();
3755 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
3756 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getInactivityExpiry() > 0) {
3757 if (DBG) {
3758 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
3759 log("Setting inactive " + nai.toShortString() + " for " + lingerTime + "ms");
3760 }
3761 nai.setInactive();
3762 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
3763 return true;
3764 }
3765 return false;
3766 }
3767
3768 private void handleNetworkAgentRegistered(Message msg) {
3769 final NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
3770 if (!mNetworkAgentInfos.contains(nai)) {
3771 return;
3772 }
3773
3774 if (msg.arg1 == NetworkAgentInfo.ARG_AGENT_SUCCESS) {
3775 if (VDBG) log("NetworkAgent registered");
3776 } else {
3777 loge("Error connecting NetworkAgent");
3778 mNetworkAgentInfos.remove(nai);
3779 if (nai != null) {
3780 final boolean wasDefault = isDefaultNetwork(nai);
3781 synchronized (mNetworkForNetId) {
3782 mNetworkForNetId.remove(nai.network.getNetId());
3783 }
3784 mNetIdManager.releaseNetId(nai.network.getNetId());
3785 // Just in case.
3786 mLegacyTypeTracker.remove(nai, wasDefault);
3787 }
3788 }
3789 }
3790
3791 private void handleNetworkAgentDisconnected(Message msg) {
3792 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
3793 if (mNetworkAgentInfos.contains(nai)) {
3794 disconnectAndDestroyNetwork(nai);
3795 }
3796 }
3797
3798 // Destroys a network, remove references to it from the internal state managed by
3799 // ConnectivityService, free its interfaces and clean up.
3800 // Must be called on the Handler thread.
3801 private void disconnectAndDestroyNetwork(NetworkAgentInfo nai) {
3802 ensureRunningOnConnectivityServiceThread();
3803 if (DBG) {
3804 log(nai.toShortString() + " disconnected, was satisfying " + nai.numNetworkRequests());
3805 }
3806 // Clear all notifications of this network.
3807 mNotifier.clearNotification(nai.network.getNetId());
3808 // A network agent has disconnected.
3809 // TODO - if we move the logic to the network agent (have them disconnect
3810 // because they lost all their requests or because their score isn't good)
3811 // then they would disconnect organically, report their new state and then
3812 // disconnect the channel.
3813 if (nai.networkInfo.isConnected()) {
3814 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
3815 null, null);
3816 }
3817 final boolean wasDefault = isDefaultNetwork(nai);
3818 if (wasDefault) {
3819 mDefaultInetConditionPublished = 0;
3820 }
3821 notifyIfacesChangedForNetworkStats();
3822 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
3823 // by other networks that are already connected. Perhaps that can be done by
3824 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
3825 // of rematchAllNetworksAndRequests
3826 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
3827 mKeepaliveTracker.handleStopAllKeepalives(nai, SocketKeepalive.ERROR_INVALID_NETWORK);
3828
3829 mQosCallbackTracker.handleNetworkReleased(nai.network);
3830 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
3831 // Disable wakeup packet monitoring for each interface.
3832 wakeupModifyInterface(iface, nai.networkCapabilities, false);
3833 }
3834 nai.networkMonitor().notifyNetworkDisconnected();
3835 mNetworkAgentInfos.remove(nai);
3836 nai.clatd.update();
3837 synchronized (mNetworkForNetId) {
3838 // Remove the NetworkAgent, but don't mark the netId as
3839 // available until we've told netd to delete it below.
3840 mNetworkForNetId.remove(nai.network.getNetId());
3841 }
3842 propagateUnderlyingNetworkCapabilities(nai.network);
3843 // Remove all previously satisfied requests.
3844 for (int i = 0; i < nai.numNetworkRequests(); i++) {
3845 final NetworkRequest request = nai.requestAt(i);
3846 final NetworkRequestInfo nri = mNetworkRequests.get(request);
3847 final NetworkAgentInfo currentNetwork = nri.getSatisfier();
3848 if (currentNetwork != null
3849 && currentNetwork.network.getNetId() == nai.network.getNetId()) {
3850 // uid rules for this network will be removed in destroyNativeNetwork(nai).
3851 // TODO : setting the satisfier is in fact the job of the rematch. Teach the
3852 // rematch not to keep disconnected agents instead of setting it here ; this
3853 // will also allow removing updating the offers below.
3854 nri.setSatisfier(null, null);
3855 for (final NetworkOfferInfo noi : mNetworkOffers) {
3856 informOffer(nri, noi.offer, mNetworkRanker);
3857 }
3858
3859 if (mDefaultRequest == nri) {
3860 // TODO : make battery stats aware that since 2013 multiple interfaces may be
3861 // active at the same time. For now keep calling this with the default
3862 // network, because while incorrect this is the closest to the old (also
3863 // incorrect) behavior.
3864 mNetworkActivityTracker.updateDataActivityTracking(
3865 null /* newNetwork */, nai);
3866 ensureNetworkTransitionWakelock(nai.toShortString());
3867 }
3868 }
3869 }
3870 nai.clearInactivityState();
3871 // TODO: mLegacyTypeTracker.remove seems redundant given there's a full rematch right after.
3872 // Currently, deleting it breaks tests that check for the default network disconnecting.
3873 // Find out why, fix the rematch code, and delete this.
3874 mLegacyTypeTracker.remove(nai, wasDefault);
3875 rematchAllNetworksAndRequests();
3876 mLingerMonitor.noteDisconnect(nai);
3877
3878 // Immediate teardown.
3879 if (nai.teardownDelayMs == 0) {
3880 destroyNetwork(nai);
3881 return;
3882 }
3883
3884 // Delayed teardown.
3885 try {
3886 mNetd.networkSetPermissionForNetwork(nai.network.netId, INetd.PERMISSION_SYSTEM);
3887 } catch (RemoteException e) {
3888 Log.d(TAG, "Error marking network restricted during teardown: " + e);
3889 }
3890 mHandler.postDelayed(() -> destroyNetwork(nai), nai.teardownDelayMs);
3891 }
3892
3893 private void destroyNetwork(NetworkAgentInfo nai) {
3894 if (nai.created) {
3895 // Tell netd to clean up the configuration for this network
3896 // (routing rules, DNS, etc).
3897 // This may be slow as it requires a lot of netd shelling out to ip and
3898 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
3899 // after we've rematched networks with requests (which might change the default
3900 // network or service a new request from an app), so network traffic isn't interrupted
3901 // for an unnecessarily long time.
3902 destroyNativeNetwork(nai);
3903 mDnsManager.removeNetwork(nai.network);
3904 }
3905 mNetIdManager.releaseNetId(nai.network.getNetId());
3906 nai.onNetworkDestroyed();
3907 }
3908
3909 private boolean createNativeNetwork(@NonNull NetworkAgentInfo nai) {
3910 try {
3911 // This should never fail. Specifying an already in use NetID will cause failure.
3912 final NativeNetworkConfig config;
3913 if (nai.isVPN()) {
3914 if (getVpnType(nai) == VpnManager.TYPE_VPN_NONE) {
3915 Log.wtf(TAG, "Unable to get VPN type from network " + nai.toShortString());
3916 return false;
3917 }
3918 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.VIRTUAL,
3919 INetd.PERMISSION_NONE,
3920 (nai.networkAgentConfig == null || !nai.networkAgentConfig.allowBypass),
3921 getVpnType(nai));
3922 } else {
3923 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.PHYSICAL,
3924 getNetworkPermission(nai.networkCapabilities), /*secure=*/ false,
3925 VpnManager.TYPE_VPN_NONE);
3926 }
3927 mNetd.networkCreate(config);
3928 mDnsResolver.createNetworkCache(nai.network.getNetId());
3929 mDnsManager.updateTransportsForNetwork(nai.network.getNetId(),
3930 nai.networkCapabilities.getTransportTypes());
3931 return true;
3932 } catch (RemoteException | ServiceSpecificException e) {
3933 loge("Error creating network " + nai.toShortString() + ": " + e.getMessage());
3934 return false;
3935 }
3936 }
3937
3938 private void destroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
3939 try {
3940 mNetd.networkDestroy(nai.network.getNetId());
3941 } catch (RemoteException | ServiceSpecificException e) {
3942 loge("Exception destroying network(networkDestroy): " + e);
3943 }
3944 try {
3945 mDnsResolver.destroyNetworkCache(nai.network.getNetId());
3946 } catch (RemoteException | ServiceSpecificException e) {
3947 loge("Exception destroying network: " + e);
3948 }
3949 }
3950
3951 // If this method proves to be too slow then we can maintain a separate
3952 // pendingIntent => NetworkRequestInfo map.
3953 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
3954 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
3955 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
3956 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
3957 if (existingPendingIntent != null &&
Remi NGUYEN VANff55aeb2021-06-16 11:37:53 +00003958 mDeps.intentFilterEquals(existingPendingIntent, pendingIntent)) {
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00003959 return entry.getValue();
3960 }
3961 }
3962 return null;
3963 }
3964
3965 private void handleRegisterNetworkRequestWithIntent(@NonNull final Message msg) {
3966 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
3967 // handleRegisterNetworkRequestWithIntent() doesn't apply to multilayer requests.
3968 ensureNotMultilayerRequest(nri, "handleRegisterNetworkRequestWithIntent");
3969 final NetworkRequestInfo existingRequest =
3970 findExistingNetworkRequestInfo(nri.mPendingIntent);
3971 if (existingRequest != null) { // remove the existing request.
3972 if (DBG) {
3973 log("Replacing " + existingRequest.mRequests.get(0) + " with "
3974 + nri.mRequests.get(0) + " because their intents matched.");
3975 }
3976 handleReleaseNetworkRequest(existingRequest.mRequests.get(0), mDeps.getCallingUid(),
3977 /* callOnUnavailable */ false);
3978 }
3979 handleRegisterNetworkRequest(nri);
3980 }
3981
3982 private void handleRegisterNetworkRequest(@NonNull final NetworkRequestInfo nri) {
3983 handleRegisterNetworkRequests(Collections.singleton(nri));
3984 }
3985
3986 private void handleRegisterNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
3987 ensureRunningOnConnectivityServiceThread();
3988 for (final NetworkRequestInfo nri : nris) {
3989 mNetworkRequestInfoLogs.log("REGISTER " + nri);
3990 for (final NetworkRequest req : nri.mRequests) {
3991 mNetworkRequests.put(req, nri);
3992 // TODO: Consider update signal strength for other types.
3993 if (req.isListen()) {
3994 for (final NetworkAgentInfo network : mNetworkAgentInfos) {
3995 if (req.networkCapabilities.hasSignalStrength()
3996 && network.satisfiesImmutableCapabilitiesOf(req)) {
3997 updateSignalStrengthThresholds(network, "REGISTER", req);
3998 }
3999 }
4000 }
4001 }
4002 // If this NRI has a satisfier already, it is replacing an older request that
4003 // has been removed. Track it.
4004 final NetworkRequest activeRequest = nri.getActiveRequest();
4005 if (null != activeRequest) {
4006 // If there is an active request, then for sure there is a satisfier.
4007 nri.getSatisfier().addRequest(activeRequest);
4008 }
4009 }
4010
4011 rematchAllNetworksAndRequests();
4012
4013 // Requests that have not been matched to a network will not have been sent to the
4014 // providers, because the old satisfier and the new satisfier are the same (null in this
4015 // case). Send these requests to the providers.
4016 for (final NetworkRequestInfo nri : nris) {
4017 for (final NetworkOfferInfo noi : mNetworkOffers) {
4018 informOffer(nri, noi.offer, mNetworkRanker);
4019 }
4020 }
4021 }
4022
4023 private void handleReleaseNetworkRequestWithIntent(@NonNull final PendingIntent pendingIntent,
4024 final int callingUid) {
4025 final NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
4026 if (nri != null) {
4027 // handleReleaseNetworkRequestWithIntent() paths don't apply to multilayer requests.
4028 ensureNotMultilayerRequest(nri, "handleReleaseNetworkRequestWithIntent");
4029 handleReleaseNetworkRequest(
4030 nri.mRequests.get(0),
4031 callingUid,
4032 /* callOnUnavailable */ false);
4033 }
4034 }
4035
4036 // Determines whether the network is the best (or could become the best, if it validated), for
4037 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
4038 // on the value of reason:
4039 //
4040 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
4041 // then it should be torn down.
4042 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
4043 // then it should be lingered.
4044 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
4045 ensureRunningOnConnectivityServiceThread();
4046
4047 if (!nai.everConnected || nai.isVPN() || nai.isInactive()
4048 || nai.getScore().getKeepConnectedReason() != NetworkScore.KEEP_CONNECTED_NONE) {
4049 return false;
4050 }
4051
4052 final int numRequests;
4053 switch (reason) {
4054 case TEARDOWN:
4055 numRequests = nai.numRequestNetworkRequests();
4056 break;
4057 case LINGER:
4058 numRequests = nai.numForegroundNetworkRequests();
4059 break;
4060 default:
4061 Log.wtf(TAG, "Invalid reason. Cannot happen.");
4062 return true;
4063 }
4064
4065 if (numRequests > 0) return false;
4066
4067 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4068 if (reason == UnneededFor.LINGER
4069 && !nri.isMultilayerRequest()
4070 && nri.mRequests.get(0).isBackgroundRequest()) {
4071 // Background requests don't affect lingering.
4072 continue;
4073 }
4074
4075 if (isNetworkPotentialSatisfier(nai, nri)) {
4076 return false;
4077 }
4078 }
4079 return true;
4080 }
4081
4082 private boolean isNetworkPotentialSatisfier(
4083 @NonNull final NetworkAgentInfo candidate, @NonNull final NetworkRequestInfo nri) {
4084 // listen requests won't keep up a network satisfying it. If this is not a multilayer
4085 // request, return immediately. For multilayer requests, check to see if any of the
4086 // multilayer requests may have a potential satisfier.
4087 if (!nri.isMultilayerRequest() && (nri.mRequests.get(0).isListen()
4088 || nri.mRequests.get(0).isListenForBest())) {
4089 return false;
4090 }
4091 for (final NetworkRequest req : nri.mRequests) {
4092 // This multilayer listen request is satisfied therefore no further requests need to be
4093 // evaluated deeming this network not a potential satisfier.
4094 if ((req.isListen() || req.isListenForBest()) && nri.getActiveRequest() == req) {
4095 return false;
4096 }
4097 // As non-multilayer listen requests have already returned, the below would only happen
4098 // for a multilayer request therefore continue to the next request if available.
4099 if (req.isListen() || req.isListenForBest()) {
4100 continue;
4101 }
4102 // If this Network is already the highest scoring Network for a request, or if
4103 // there is hope for it to become one if it validated, then it is needed.
4104 if (candidate.satisfies(req)) {
4105 // As soon as a network is found that satisfies a request, return. Specifically for
4106 // multilayer requests, returning as soon as a NetworkAgentInfo satisfies a request
4107 // is important so as to not evaluate lower priority requests further in
4108 // nri.mRequests.
4109 final NetworkAgentInfo champion = req.equals(nri.getActiveRequest())
4110 ? nri.getSatisfier() : null;
4111 // Note that this catches two important cases:
4112 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
4113 // is currently satisfying the request. This is desirable when
4114 // cellular ends up validating but WiFi does not.
4115 // 2. Unvalidated WiFi will not be reaped when validated cellular
4116 // is currently satisfying the request. This is desirable when
4117 // WiFi ends up validating and out scoring cellular.
4118 return mNetworkRanker.mightBeat(req, champion, candidate.getValidatedScoreable());
4119 }
4120 }
4121
4122 return false;
4123 }
4124
4125 private NetworkRequestInfo getNriForAppRequest(
4126 NetworkRequest request, int callingUid, String requestedOperation) {
4127 // Looking up the app passed param request in mRequests isn't possible since it may return
4128 // null for a request managed by a per-app default. Therefore use getNriForAppRequest() to
4129 // do the lookup since that will also find per-app default managed requests.
4130 // Additionally, this lookup needs to be relatively fast (hence the lookup optimization)
4131 // to avoid potential race conditions when validating a package->uid mapping when sending
4132 // the callback on the very low-chance that an application shuts down prior to the callback
4133 // being sent.
4134 final NetworkRequestInfo nri = mNetworkRequests.get(request) != null
4135 ? mNetworkRequests.get(request) : getNriForAppRequest(request);
4136
4137 if (nri != null) {
4138 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
4139 log(String.format("UID %d attempted to %s for unowned request %s",
4140 callingUid, requestedOperation, nri));
4141 return null;
4142 }
4143 }
4144
4145 return nri;
4146 }
4147
4148 private void ensureNotMultilayerRequest(@NonNull final NetworkRequestInfo nri,
4149 final String callingMethod) {
4150 if (nri.isMultilayerRequest()) {
4151 throw new IllegalStateException(
4152 callingMethod + " does not support multilayer requests.");
4153 }
4154 }
4155
4156 private void handleTimedOutNetworkRequest(@NonNull final NetworkRequestInfo nri) {
4157 ensureRunningOnConnectivityServiceThread();
4158 // handleTimedOutNetworkRequest() is part of the requestNetwork() flow which works off of a
4159 // single NetworkRequest and thus does not apply to multilayer requests.
4160 ensureNotMultilayerRequest(nri, "handleTimedOutNetworkRequest");
4161 if (mNetworkRequests.get(nri.mRequests.get(0)) == null) {
4162 return;
4163 }
4164 if (nri.isBeingSatisfied()) {
4165 return;
4166 }
4167 if (VDBG || (DBG && nri.mRequests.get(0).isRequest())) {
4168 log("releasing " + nri.mRequests.get(0) + " (timeout)");
4169 }
4170 handleRemoveNetworkRequest(nri);
4171 callCallbackForRequest(
4172 nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
4173 }
4174
4175 private void handleReleaseNetworkRequest(@NonNull final NetworkRequest request,
4176 final int callingUid,
4177 final boolean callOnUnavailable) {
4178 final NetworkRequestInfo nri =
4179 getNriForAppRequest(request, callingUid, "release NetworkRequest");
4180 if (nri == null) {
4181 return;
4182 }
4183 if (VDBG || (DBG && request.isRequest())) {
4184 log("releasing " + request + " (release request)");
4185 }
4186 handleRemoveNetworkRequest(nri);
4187 if (callOnUnavailable) {
4188 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
4189 }
4190 }
4191
4192 private void handleRemoveNetworkRequest(@NonNull final NetworkRequestInfo nri) {
4193 ensureRunningOnConnectivityServiceThread();
4194 nri.unlinkDeathRecipient();
4195 for (final NetworkRequest req : nri.mRequests) {
4196 mNetworkRequests.remove(req);
4197 if (req.isListen()) {
4198 removeListenRequestFromNetworks(req);
4199 }
4200 }
4201 if (mDefaultNetworkRequests.remove(nri)) {
4202 // If this request was one of the defaults, then the UID rules need to be updated
4203 // WARNING : if the app(s) for which this network request is the default are doing
4204 // traffic, this will kill their connected sockets, even if an equivalent request
4205 // is going to be reinstated right away ; unconnected traffic will go on the default
4206 // until the new default is set, which will happen very soon.
4207 // TODO : The only way out of this is to diff old defaults and new defaults, and only
4208 // remove ranges for those requests that won't have a replacement
4209 final NetworkAgentInfo satisfier = nri.getSatisfier();
4210 if (null != satisfier) {
4211 try {
paulhude2a2392021-06-09 16:11:35 +08004212 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
4213 satisfier.network.getNetId(),
4214 toUidRangeStableParcels(nri.getUids()),
4215 nri.getDefaultNetworkPriority()));
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00004216 } catch (RemoteException e) {
4217 loge("Exception setting network preference default network", e);
4218 }
4219 }
4220 }
4221 nri.decrementRequestCount();
4222 mNetworkRequestInfoLogs.log("RELEASE " + nri);
4223
4224 if (null != nri.getActiveRequest()) {
4225 if (!nri.getActiveRequest().isListen()) {
4226 removeSatisfiedNetworkRequestFromNetwork(nri);
4227 } else {
4228 nri.setSatisfier(null, null);
4229 }
4230 }
4231
4232 // For all outstanding offers, cancel any of the layers of this NRI that used to be
4233 // needed for this offer.
4234 for (final NetworkOfferInfo noi : mNetworkOffers) {
4235 for (final NetworkRequest req : nri.mRequests) {
4236 if (req.isRequest() && noi.offer.neededFor(req)) {
4237 noi.offer.onNetworkUnneeded(req);
4238 }
4239 }
4240 }
4241 }
4242
4243 private void handleRemoveNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
4244 for (final NetworkRequestInfo nri : nris) {
4245 if (mDefaultRequest == nri) {
4246 // Make sure we never remove the default request.
4247 continue;
4248 }
4249 handleRemoveNetworkRequest(nri);
4250 }
4251 }
4252
4253 private void removeListenRequestFromNetworks(@NonNull final NetworkRequest req) {
4254 // listens don't have a singular affected Network. Check all networks to see
4255 // if this listen request applies and remove it.
4256 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
4257 nai.removeRequest(req.requestId);
4258 if (req.networkCapabilities.hasSignalStrength()
4259 && nai.satisfiesImmutableCapabilitiesOf(req)) {
4260 updateSignalStrengthThresholds(nai, "RELEASE", req);
4261 }
4262 }
4263 }
4264
4265 /**
4266 * Remove a NetworkRequestInfo's satisfied request from its 'satisfier' (NetworkAgentInfo) and
4267 * manage the necessary upkeep (linger, teardown networks, etc.) when doing so.
4268 * @param nri the NetworkRequestInfo to disassociate from its current NetworkAgentInfo
4269 */
4270 private void removeSatisfiedNetworkRequestFromNetwork(@NonNull final NetworkRequestInfo nri) {
4271 boolean wasKept = false;
4272 final NetworkAgentInfo nai = nri.getSatisfier();
4273 if (nai != null) {
4274 final int requestLegacyType = nri.getActiveRequest().legacyType;
4275 final boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
4276 nai.removeRequest(nri.getActiveRequest().requestId);
4277 if (VDBG || DDBG) {
4278 log(" Removing from current network " + nai.toShortString()
4279 + ", leaving " + nai.numNetworkRequests() + " requests.");
4280 }
4281 // If there are still lingered requests on this network, don't tear it down,
4282 // but resume lingering instead.
4283 final long now = SystemClock.elapsedRealtime();
4284 if (updateInactivityState(nai, now)) {
4285 notifyNetworkLosing(nai, now);
4286 }
4287 if (unneeded(nai, UnneededFor.TEARDOWN)) {
4288 if (DBG) log("no live requests for " + nai.toShortString() + "; disconnecting");
4289 teardownUnneededNetwork(nai);
4290 } else {
4291 wasKept = true;
4292 }
4293 nri.setSatisfier(null, null);
4294 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
4295 // Went from foreground to background.
4296 updateCapabilitiesForNetwork(nai);
4297 }
4298
4299 // Maintain the illusion. When this request arrived, we might have pretended
4300 // that a network connected to serve it, even though the network was already
4301 // connected. Now that this request has gone away, we might have to pretend
4302 // that the network disconnected. LegacyTypeTracker will generate that
4303 // phantom disconnect for this type.
4304 if (requestLegacyType != TYPE_NONE) {
4305 boolean doRemove = true;
4306 if (wasKept) {
4307 // check if any of the remaining requests for this network are for the
4308 // same legacy type - if so, don't remove the nai
4309 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4310 NetworkRequest otherRequest = nai.requestAt(i);
4311 if (otherRequest.legacyType == requestLegacyType
4312 && otherRequest.isRequest()) {
4313 if (DBG) log(" still have other legacy request - leaving");
4314 doRemove = false;
4315 }
4316 }
4317 }
4318
4319 if (doRemove) {
4320 mLegacyTypeTracker.remove(requestLegacyType, nai, false);
4321 }
4322 }
4323 }
4324 }
4325
4326 private PerUidCounter getRequestCounter(NetworkRequestInfo nri) {
4327 return checkAnyPermissionOf(
4328 nri.mPid, nri.mUid, NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
4329 ? mSystemNetworkRequestCounter : mNetworkRequestCounter;
4330 }
4331
4332 @Override
4333 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
4334 enforceNetworkStackSettingsOrSetup();
4335 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
4336 encodeBool(accept), encodeBool(always), network));
4337 }
4338
4339 @Override
4340 public void setAcceptPartialConnectivity(Network network, boolean accept, boolean always) {
4341 enforceNetworkStackSettingsOrSetup();
4342 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY,
4343 encodeBool(accept), encodeBool(always), network));
4344 }
4345
4346 @Override
4347 public void setAvoidUnvalidated(Network network) {
4348 enforceNetworkStackSettingsOrSetup();
4349 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
4350 }
4351
Chiachang Wangfad30e32021-06-23 02:08:44 +00004352 @Override
4353 public void setTestAllowBadWifiUntil(long timeMs) {
4354 enforceSettingsPermission();
4355 if (!Build.isDebuggable()) {
4356 throw new IllegalStateException("Does not support in non-debuggable build");
4357 }
4358
4359 if (timeMs > System.currentTimeMillis() + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS) {
4360 throw new IllegalArgumentException("It should not exceed "
4361 + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS + "ms from now");
4362 }
4363
4364 mHandler.sendMessage(
4365 mHandler.obtainMessage(EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL, timeMs));
4366 }
4367
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00004368 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
4369 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
4370 " accept=" + accept + " always=" + always);
4371
4372 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4373 if (nai == null) {
4374 // Nothing to do.
4375 return;
4376 }
4377
4378 if (nai.everValidated) {
4379 // The network validated while the dialog box was up. Take no action.
4380 return;
4381 }
4382
4383 if (!nai.networkAgentConfig.explicitlySelected) {
4384 Log.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
4385 }
4386
4387 if (accept != nai.networkAgentConfig.acceptUnvalidated) {
4388 nai.networkAgentConfig.acceptUnvalidated = accept;
4389 // If network becomes partial connectivity and user already accepted to use this
4390 // network, we should respect the user's option and don't need to popup the
4391 // PARTIAL_CONNECTIVITY notification to user again.
4392 nai.networkAgentConfig.acceptPartialConnectivity = accept;
4393 nai.updateScoreForNetworkAgentUpdate();
4394 rematchAllNetworksAndRequests();
4395 }
4396
4397 if (always) {
4398 nai.onSaveAcceptUnvalidated(accept);
4399 }
4400
4401 if (!accept) {
4402 // Tell the NetworkAgent to not automatically reconnect to the network.
4403 nai.onPreventAutomaticReconnect();
4404 // Teardown the network.
4405 teardownUnneededNetwork(nai);
4406 }
4407
4408 }
4409
4410 private void handleSetAcceptPartialConnectivity(Network network, boolean accept,
4411 boolean always) {
4412 if (DBG) {
4413 log("handleSetAcceptPartialConnectivity network=" + network + " accept=" + accept
4414 + " always=" + always);
4415 }
4416
4417 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4418 if (nai == null) {
4419 // Nothing to do.
4420 return;
4421 }
4422
4423 if (nai.lastValidated) {
4424 // The network validated while the dialog box was up. Take no action.
4425 return;
4426 }
4427
4428 if (accept != nai.networkAgentConfig.acceptPartialConnectivity) {
4429 nai.networkAgentConfig.acceptPartialConnectivity = accept;
4430 }
4431
4432 // TODO: Use the current design or save the user choice into IpMemoryStore.
4433 if (always) {
4434 nai.onSaveAcceptUnvalidated(accept);
4435 }
4436
4437 if (!accept) {
4438 // Tell the NetworkAgent to not automatically reconnect to the network.
4439 nai.onPreventAutomaticReconnect();
4440 // Tear down the network.
4441 teardownUnneededNetwork(nai);
4442 } else {
4443 // Inform NetworkMonitor that partial connectivity is acceptable. This will likely
4444 // result in a partial connectivity result which will be processed by
4445 // maybeHandleNetworkMonitorMessage.
4446 //
4447 // TODO: NetworkMonitor does not refer to the "never ask again" bit. The bit is stored
4448 // per network. Therefore, NetworkMonitor may still do https probe.
4449 nai.networkMonitor().setAcceptPartialConnectivity();
4450 }
4451 }
4452
4453 private void handleSetAvoidUnvalidated(Network network) {
4454 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4455 if (nai == null || nai.lastValidated) {
4456 // Nothing to do. The network either disconnected or revalidated.
4457 return;
4458 }
4459 if (!nai.avoidUnvalidated) {
4460 nai.avoidUnvalidated = true;
4461 nai.updateScoreForNetworkAgentUpdate();
4462 rematchAllNetworksAndRequests();
4463 }
4464 }
4465
4466 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
4467 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
4468 mHandler.sendMessageDelayed(
4469 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
4470 PROMPT_UNVALIDATED_DELAY_MS);
4471 }
4472
4473 @Override
4474 public void startCaptivePortalApp(Network network) {
4475 enforceNetworkStackOrSettingsPermission();
4476 mHandler.post(() -> {
4477 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4478 if (nai == null) return;
4479 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
4480 nai.networkMonitor().launchCaptivePortalApp();
4481 });
4482 }
4483
4484 /**
4485 * NetworkStack endpoint to start the captive portal app. The NetworkStack needs to use this
4486 * endpoint as it does not have INTERACT_ACROSS_USERS_FULL itself.
4487 * @param network Network on which the captive portal was detected.
4488 * @param appExtras Bundle to use as intent extras for the captive portal application.
4489 * Must be treated as opaque to avoid preventing the captive portal app to
4490 * update its arguments.
4491 */
4492 @Override
4493 public void startCaptivePortalAppInternal(Network network, Bundle appExtras) {
4494 mContext.enforceCallingOrSelfPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4495 "ConnectivityService");
4496
4497 final Intent appIntent = new Intent(ConnectivityManager.ACTION_CAPTIVE_PORTAL_SIGN_IN);
4498 appIntent.putExtras(appExtras);
4499 appIntent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL,
4500 new CaptivePortal(new CaptivePortalImpl(network).asBinder()));
4501 appIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
4502
4503 final long token = Binder.clearCallingIdentity();
4504 try {
4505 mContext.startActivityAsUser(appIntent, UserHandle.CURRENT);
4506 } finally {
4507 Binder.restoreCallingIdentity(token);
4508 }
4509 }
4510
4511 private class CaptivePortalImpl extends ICaptivePortal.Stub {
4512 private final Network mNetwork;
4513
4514 private CaptivePortalImpl(Network network) {
4515 mNetwork = network;
4516 }
4517
4518 @Override
4519 public void appResponse(final int response) {
4520 if (response == CaptivePortal.APP_RETURN_WANTED_AS_IS) {
4521 enforceSettingsPermission();
4522 }
4523
4524 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
4525 if (nm == null) return;
4526 nm.notifyCaptivePortalAppFinished(response);
4527 }
4528
4529 @Override
4530 public void appRequest(final int request) {
4531 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
4532 if (nm == null) return;
4533
4534 if (request == CaptivePortal.APP_REQUEST_REEVALUATION_REQUIRED) {
4535 checkNetworkStackPermission();
4536 nm.forceReevaluation(mDeps.getCallingUid());
4537 }
4538 }
4539
4540 @Nullable
4541 private NetworkMonitorManager getNetworkMonitorManager(final Network network) {
4542 // getNetworkAgentInfoForNetwork is thread-safe
4543 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4544 if (nai == null) return null;
4545
4546 // nai.networkMonitor() is thread-safe
4547 return nai.networkMonitor();
4548 }
4549 }
4550
4551 public boolean avoidBadWifi() {
4552 return mMultinetworkPolicyTracker.getAvoidBadWifi();
4553 }
4554
4555 /**
4556 * Return whether the device should maintain continuous, working connectivity by switching away
4557 * from WiFi networks having no connectivity.
4558 * @see MultinetworkPolicyTracker#getAvoidBadWifi()
4559 */
4560 public boolean shouldAvoidBadWifi() {
4561 if (!checkNetworkStackPermission()) {
4562 throw new SecurityException("avoidBadWifi requires NETWORK_STACK permission");
4563 }
4564 return avoidBadWifi();
4565 }
4566
4567 private void updateAvoidBadWifi() {
4568 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
4569 nai.updateScoreForNetworkAgentUpdate();
4570 }
4571 rematchAllNetworksAndRequests();
4572 }
4573
4574 // TODO: Evaluate whether this is of interest to other consumers of
4575 // MultinetworkPolicyTracker and worth moving out of here.
4576 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
4577 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
4578 if (!configRestrict) {
4579 pw.println("Bad Wi-Fi avoidance: unrestricted");
4580 return;
4581 }
4582
4583 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
4584 pw.increaseIndent();
4585 pw.println("Config restrict: " + configRestrict);
4586
4587 final String value = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
4588 String description;
4589 // Can't use a switch statement because strings are legal case labels, but null is not.
4590 if ("0".equals(value)) {
4591 description = "get stuck";
4592 } else if (value == null) {
4593 description = "prompt";
4594 } else if ("1".equals(value)) {
4595 description = "avoid";
4596 } else {
4597 description = value + " (?)";
4598 }
4599 pw.println("User setting: " + description);
4600 pw.println("Network overrides:");
4601 pw.increaseIndent();
4602 for (NetworkAgentInfo nai : networksSortedById()) {
4603 if (nai.avoidUnvalidated) {
4604 pw.println(nai.toShortString());
4605 }
4606 }
4607 pw.decreaseIndent();
4608 pw.decreaseIndent();
4609 }
4610
4611 // TODO: This method is copied from TetheringNotificationUpdater. Should have a utility class to
4612 // unify the method.
4613 private static @NonNull String getSettingsPackageName(@NonNull final PackageManager pm) {
4614 final Intent settingsIntent = new Intent(Settings.ACTION_SETTINGS);
4615 final ComponentName settingsComponent = settingsIntent.resolveActivity(pm);
4616 return settingsComponent != null
4617 ? settingsComponent.getPackageName() : "com.android.settings";
4618 }
4619
4620 private void showNetworkNotification(NetworkAgentInfo nai, NotificationType type) {
4621 final String action;
4622 final boolean highPriority;
4623 switch (type) {
4624 case NO_INTERNET:
4625 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
4626 // High priority because it is only displayed for explicitly selected networks.
4627 highPriority = true;
4628 break;
4629 case PRIVATE_DNS_BROKEN:
4630 action = Settings.ACTION_WIRELESS_SETTINGS;
4631 // High priority because we should let user know why there is no internet.
4632 highPriority = true;
4633 break;
4634 case LOST_INTERNET:
4635 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
4636 // High priority because it could help the user avoid unexpected data usage.
4637 highPriority = true;
4638 break;
4639 case PARTIAL_CONNECTIVITY:
4640 action = ConnectivityManager.ACTION_PROMPT_PARTIAL_CONNECTIVITY;
4641 // Don't bother the user with a high-priority notification if the network was not
4642 // explicitly selected by the user.
4643 highPriority = nai.networkAgentConfig.explicitlySelected;
4644 break;
4645 default:
4646 Log.wtf(TAG, "Unknown notification type " + type);
4647 return;
4648 }
4649
4650 Intent intent = new Intent(action);
4651 if (type != NotificationType.PRIVATE_DNS_BROKEN) {
4652 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, nai.network);
4653 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4654 // Some OEMs have their own Settings package. Thus, need to get the current using
4655 // Settings package name instead of just use default name "com.android.settings".
4656 final String settingsPkgName = getSettingsPackageName(mContext.getPackageManager());
4657 intent.setClassName(settingsPkgName,
4658 settingsPkgName + ".wifi.WifiNoInternetDialog");
4659 }
4660
4661 PendingIntent pendingIntent = PendingIntent.getActivity(
4662 mContext.createContextAsUser(UserHandle.CURRENT, 0 /* flags */),
4663 0 /* requestCode */,
4664 intent,
4665 PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE);
4666
4667 mNotifier.showNotification(
4668 nai.network.getNetId(), type, nai, null, pendingIntent, highPriority);
4669 }
4670
4671 private boolean shouldPromptUnvalidated(NetworkAgentInfo nai) {
4672 // Don't prompt if the network is validated, and don't prompt on captive portals
4673 // because we're already prompting the user to sign in.
4674 if (nai.everValidated || nai.everCaptivePortalDetected) {
4675 return false;
4676 }
4677
4678 // If a network has partial connectivity, always prompt unless the user has already accepted
4679 // partial connectivity and selected don't ask again. This ensures that if the device
4680 // automatically connects to a network that has partial Internet access, the user will
4681 // always be able to use it, either because they've already chosen "don't ask again" or
4682 // because we have prompt them.
4683 if (nai.partialConnectivity && !nai.networkAgentConfig.acceptPartialConnectivity) {
4684 return true;
4685 }
4686
4687 // If a network has no Internet access, only prompt if the network was explicitly selected
4688 // and if the user has not already told us to use the network regardless of whether it
4689 // validated or not.
4690 if (nai.networkAgentConfig.explicitlySelected
4691 && !nai.networkAgentConfig.acceptUnvalidated) {
4692 return true;
4693 }
4694
4695 return false;
4696 }
4697
4698 private void handlePromptUnvalidated(Network network) {
4699 if (VDBG || DDBG) log("handlePromptUnvalidated " + network);
4700 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4701
4702 if (nai == null || !shouldPromptUnvalidated(nai)) {
4703 return;
4704 }
4705
4706 // Stop automatically reconnecting to this network in the future. Automatically connecting
4707 // to a network that provides no or limited connectivity is not useful, because the user
4708 // cannot use that network except through the notification shown by this method, and the
4709 // notification is only shown if the network is explicitly selected by the user.
4710 nai.onPreventAutomaticReconnect();
4711
4712 // TODO: Evaluate if it's needed to wait 8 seconds for triggering notification when
4713 // NetworkMonitor detects the network is partial connectivity. Need to change the design to
4714 // popup the notification immediately when the network is partial connectivity.
4715 if (nai.partialConnectivity) {
4716 showNetworkNotification(nai, NotificationType.PARTIAL_CONNECTIVITY);
4717 } else {
4718 showNetworkNotification(nai, NotificationType.NO_INTERNET);
4719 }
4720 }
4721
4722 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
4723 NetworkCapabilities nc = nai.networkCapabilities;
4724 if (DBG) log("handleNetworkUnvalidated " + nai.toShortString() + " cap=" + nc);
4725
4726 if (!nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
4727 return;
4728 }
4729
4730 if (mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
4731 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
4732 }
4733 }
4734
4735 @Override
4736 public int getMultipathPreference(Network network) {
4737 enforceAccessPermission();
4738
4739 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4740 if (nai != null && nai.networkCapabilities
4741 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
4742 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
4743 }
4744
4745 final NetworkPolicyManager netPolicyManager =
4746 mContext.getSystemService(NetworkPolicyManager.class);
4747
4748 final long token = Binder.clearCallingIdentity();
4749 final int networkPreference;
4750 try {
4751 networkPreference = netPolicyManager.getMultipathPreference(network);
4752 } finally {
4753 Binder.restoreCallingIdentity(token);
4754 }
4755 if (networkPreference != 0) {
4756 return networkPreference;
4757 }
4758 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
4759 }
4760
4761 @Override
4762 public NetworkRequest getDefaultRequest() {
4763 return mDefaultRequest.mRequests.get(0);
4764 }
4765
4766 private class InternalHandler extends Handler {
4767 public InternalHandler(Looper looper) {
4768 super(looper);
4769 }
4770
4771 @Override
4772 public void handleMessage(Message msg) {
4773 switch (msg.what) {
4774 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
4775 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
4776 handleReleaseNetworkTransitionWakelock(msg.what);
4777 break;
4778 }
4779 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
4780 mProxyTracker.loadDeprecatedGlobalHttpProxy();
4781 break;
4782 }
4783 case EVENT_PROXY_HAS_CHANGED: {
4784 final Pair<Network, ProxyInfo> arg = (Pair<Network, ProxyInfo>) msg.obj;
4785 handleApplyDefaultProxy(arg.second);
4786 break;
4787 }
4788 case EVENT_REGISTER_NETWORK_PROVIDER: {
4789 handleRegisterNetworkProvider((NetworkProviderInfo) msg.obj);
4790 break;
4791 }
4792 case EVENT_UNREGISTER_NETWORK_PROVIDER: {
4793 handleUnregisterNetworkProvider((Messenger) msg.obj);
4794 break;
4795 }
4796 case EVENT_REGISTER_NETWORK_OFFER: {
4797 handleRegisterNetworkOffer((NetworkOffer) msg.obj);
4798 break;
4799 }
4800 case EVENT_UNREGISTER_NETWORK_OFFER: {
4801 final NetworkOfferInfo offer =
4802 findNetworkOfferInfoByCallback((INetworkOfferCallback) msg.obj);
4803 if (null != offer) {
4804 handleUnregisterNetworkOffer(offer);
4805 }
4806 break;
4807 }
4808 case EVENT_REGISTER_NETWORK_AGENT: {
4809 final Pair<NetworkAgentInfo, INetworkMonitor> arg =
4810 (Pair<NetworkAgentInfo, INetworkMonitor>) msg.obj;
4811 handleRegisterNetworkAgent(arg.first, arg.second);
4812 break;
4813 }
4814 case EVENT_REGISTER_NETWORK_REQUEST:
4815 case EVENT_REGISTER_NETWORK_LISTENER: {
4816 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
4817 break;
4818 }
4819 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
4820 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
4821 handleRegisterNetworkRequestWithIntent(msg);
4822 break;
4823 }
4824 case EVENT_TIMEOUT_NETWORK_REQUEST: {
4825 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
4826 handleTimedOutNetworkRequest(nri);
4827 break;
4828 }
4829 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
4830 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
4831 break;
4832 }
4833 case EVENT_RELEASE_NETWORK_REQUEST: {
4834 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1,
4835 /* callOnUnavailable */ false);
4836 break;
4837 }
4838 case EVENT_SET_ACCEPT_UNVALIDATED: {
4839 Network network = (Network) msg.obj;
4840 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
4841 break;
4842 }
4843 case EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY: {
4844 Network network = (Network) msg.obj;
4845 handleSetAcceptPartialConnectivity(network, toBool(msg.arg1),
4846 toBool(msg.arg2));
4847 break;
4848 }
4849 case EVENT_SET_AVOID_UNVALIDATED: {
4850 handleSetAvoidUnvalidated((Network) msg.obj);
4851 break;
4852 }
4853 case EVENT_PROMPT_UNVALIDATED: {
4854 handlePromptUnvalidated((Network) msg.obj);
4855 break;
4856 }
4857 case EVENT_CONFIGURE_ALWAYS_ON_NETWORKS: {
4858 handleConfigureAlwaysOnNetworks();
4859 break;
4860 }
4861 // Sent by KeepaliveTracker to process an app request on the state machine thread.
4862 case NetworkAgent.CMD_START_SOCKET_KEEPALIVE: {
4863 mKeepaliveTracker.handleStartKeepalive(msg);
4864 break;
4865 }
4866 // Sent by KeepaliveTracker to process an app request on the state machine thread.
4867 case NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE: {
4868 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
4869 int slot = msg.arg1;
4870 int reason = msg.arg2;
4871 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
4872 break;
4873 }
4874 case EVENT_REVALIDATE_NETWORK: {
4875 handleReportNetworkConnectivity((Network) msg.obj, msg.arg1, toBool(msg.arg2));
4876 break;
4877 }
4878 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
4879 handlePrivateDnsSettingsChanged();
4880 break;
4881 case EVENT_PRIVATE_DNS_VALIDATION_UPDATE:
4882 handlePrivateDnsValidationUpdate(
4883 (PrivateDnsValidationUpdate) msg.obj);
4884 break;
4885 case EVENT_UID_BLOCKED_REASON_CHANGED:
4886 handleUidBlockedReasonChanged(msg.arg1, msg.arg2);
4887 break;
4888 case EVENT_SET_REQUIRE_VPN_FOR_UIDS:
4889 handleSetRequireVpnForUids(toBool(msg.arg1), (UidRange[]) msg.obj);
4890 break;
4891 case EVENT_SET_OEM_NETWORK_PREFERENCE: {
4892 final Pair<OemNetworkPreferences, IOnCompleteListener> arg =
4893 (Pair<OemNetworkPreferences, IOnCompleteListener>) msg.obj;
4894 handleSetOemNetworkPreference(arg.first, arg.second);
4895 break;
4896 }
4897 case EVENT_SET_PROFILE_NETWORK_PREFERENCE: {
4898 final Pair<ProfileNetworkPreferences.Preference, IOnCompleteListener> arg =
4899 (Pair<ProfileNetworkPreferences.Preference, IOnCompleteListener>)
4900 msg.obj;
4901 handleSetProfileNetworkPreference(arg.first, arg.second);
4902 break;
4903 }
4904 case EVENT_REPORT_NETWORK_ACTIVITY:
4905 mNetworkActivityTracker.handleReportNetworkActivity();
4906 break;
paulhu71ad4f12021-05-25 14:56:27 +08004907 case EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED:
4908 handleMobileDataPreferredUidsChanged();
4909 break;
Chiachang Wangfad30e32021-06-23 02:08:44 +00004910 case EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL:
4911 final long timeMs = ((Long) msg.obj).longValue();
4912 mMultinetworkPolicyTracker.setTestAllowBadWifiUntil(timeMs);
4913 break;
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00004914 }
4915 }
4916 }
4917
4918 @Override
4919 @Deprecated
4920 public int getLastTetherError(String iface) {
4921 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
4922 Context.TETHERING_SERVICE);
4923 return tm.getLastTetherError(iface);
4924 }
4925
4926 @Override
4927 @Deprecated
4928 public String[] getTetherableIfaces() {
4929 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
4930 Context.TETHERING_SERVICE);
4931 return tm.getTetherableIfaces();
4932 }
4933
4934 @Override
4935 @Deprecated
4936 public String[] getTetheredIfaces() {
4937 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
4938 Context.TETHERING_SERVICE);
4939 return tm.getTetheredIfaces();
4940 }
4941
4942
4943 @Override
4944 @Deprecated
4945 public String[] getTetheringErroredIfaces() {
4946 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
4947 Context.TETHERING_SERVICE);
4948
4949 return tm.getTetheringErroredIfaces();
4950 }
4951
4952 @Override
4953 @Deprecated
4954 public String[] getTetherableUsbRegexs() {
4955 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
4956 Context.TETHERING_SERVICE);
4957
4958 return tm.getTetherableUsbRegexs();
4959 }
4960
4961 @Override
4962 @Deprecated
4963 public String[] getTetherableWifiRegexs() {
4964 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
4965 Context.TETHERING_SERVICE);
4966 return tm.getTetherableWifiRegexs();
4967 }
4968
4969 // Called when we lose the default network and have no replacement yet.
4970 // This will automatically be cleared after X seconds or a new default network
4971 // becomes CONNECTED, whichever happens first. The timer is started by the
4972 // first caller and not restarted by subsequent callers.
4973 private void ensureNetworkTransitionWakelock(String forWhom) {
4974 synchronized (this) {
4975 if (mNetTransitionWakeLock.isHeld()) {
4976 return;
4977 }
4978 mNetTransitionWakeLock.acquire();
4979 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
4980 mTotalWakelockAcquisitions++;
4981 }
4982 mWakelockLogs.log("ACQUIRE for " + forWhom);
4983 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
4984 final int lockTimeout = mResources.get().getInteger(
4985 R.integer.config_networkTransitionTimeout);
4986 mHandler.sendMessageDelayed(msg, lockTimeout);
4987 }
4988
4989 // Called when we gain a new default network to release the network transition wakelock in a
4990 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
4991 // message is cancelled.
4992 private void scheduleReleaseNetworkTransitionWakelock() {
4993 synchronized (this) {
4994 if (!mNetTransitionWakeLock.isHeld()) {
4995 return; // expiry message released the lock first.
4996 }
4997 }
4998 // Cancel self timeout on wakelock hold.
4999 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
5000 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
5001 mHandler.sendMessageDelayed(msg, 1000);
5002 }
5003
5004 // Called when either message of ensureNetworkTransitionWakelock or
5005 // scheduleReleaseNetworkTransitionWakelock is processed.
5006 private void handleReleaseNetworkTransitionWakelock(int eventId) {
5007 String event = eventName(eventId);
5008 synchronized (this) {
5009 if (!mNetTransitionWakeLock.isHeld()) {
5010 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
5011 Log.w(TAG, "expected Net Transition WakeLock to be held");
5012 return;
5013 }
5014 mNetTransitionWakeLock.release();
5015 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
5016 mTotalWakelockDurationMs += lockDuration;
5017 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
5018 mTotalWakelockReleases++;
5019 }
5020 mWakelockLogs.log(String.format("RELEASE (%s)", event));
5021 }
5022
5023 // 100 percent is full good, 0 is full bad.
5024 @Override
5025 public void reportInetCondition(int networkType, int percentage) {
5026 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
5027 if (nai == null) return;
5028 reportNetworkConnectivity(nai.network, percentage > 50);
5029 }
5030
5031 @Override
5032 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
5033 enforceAccessPermission();
5034 enforceInternetPermission();
5035 final int uid = mDeps.getCallingUid();
5036 final int connectivityInfo = encodeBool(hasConnectivity);
5037
5038 // Handle ConnectivityDiagnostics event before attempting to revalidate the network. This
5039 // forces an ordering of ConnectivityDiagnostics events in the case where hasConnectivity
5040 // does not match the known connectivity of the network - this causes NetworkMonitor to
5041 // revalidate the network and generate a ConnectivityDiagnostics ConnectivityReport event.
5042 final NetworkAgentInfo nai;
5043 if (network == null) {
5044 nai = getDefaultNetwork();
5045 } else {
5046 nai = getNetworkAgentInfoForNetwork(network);
5047 }
5048 if (nai != null) {
5049 mConnectivityDiagnosticsHandler.sendMessage(
5050 mConnectivityDiagnosticsHandler.obtainMessage(
5051 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
5052 connectivityInfo, 0, nai));
5053 }
5054
5055 mHandler.sendMessage(
5056 mHandler.obtainMessage(EVENT_REVALIDATE_NETWORK, uid, connectivityInfo, network));
5057 }
5058
5059 private void handleReportNetworkConnectivity(
5060 Network network, int uid, boolean hasConnectivity) {
5061 final NetworkAgentInfo nai;
5062 if (network == null) {
5063 nai = getDefaultNetwork();
5064 } else {
5065 nai = getNetworkAgentInfoForNetwork(network);
5066 }
5067 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
5068 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
5069 return;
5070 }
5071 // Revalidate if the app report does not match our current validated state.
5072 if (hasConnectivity == nai.lastValidated) {
5073 return;
5074 }
5075 if (DBG) {
5076 int netid = nai.network.getNetId();
5077 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
5078 }
5079 // Validating a network that has not yet connected could result in a call to
5080 // rematchNetworkAndRequests() which is not meant to work on such networks.
5081 if (!nai.everConnected) {
5082 return;
5083 }
5084 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
5085 if (isNetworkWithCapabilitiesBlocked(nc, uid, false)) {
5086 return;
5087 }
5088 nai.networkMonitor().forceReevaluation(uid);
5089 }
5090
5091 // TODO: call into netd.
5092 private boolean queryUserAccess(int uid, Network network) {
5093 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5094 if (nai == null) return false;
5095
5096 // Any UID can use its default network.
5097 if (nai == getDefaultNetworkForUid(uid)) return true;
5098
5099 // Privileged apps can use any network.
5100 if (mPermissionMonitor.hasRestrictedNetworksPermission(uid)) {
5101 return true;
5102 }
5103
5104 // An unprivileged UID can use a VPN iff the VPN applies to it.
5105 if (nai.isVPN()) {
5106 return nai.networkCapabilities.appliesToUid(uid);
5107 }
5108
5109 // An unprivileged UID can bypass the VPN that applies to it only if it can protect its
5110 // sockets, i.e., if it is the owner.
5111 final NetworkAgentInfo vpn = getVpnForUid(uid);
5112 if (vpn != null && !vpn.networkAgentConfig.allowBypass
5113 && uid != vpn.networkCapabilities.getOwnerUid()) {
5114 return false;
5115 }
5116
5117 // The UID's permission must be at least sufficient for the network. Since the restricted
5118 // permission was already checked above, that just leaves background networks.
5119 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
5120 return mPermissionMonitor.hasUseBackgroundNetworksPermission(uid);
5121 }
5122
5123 // Unrestricted network. Anyone gets to use it.
5124 return true;
5125 }
5126
5127 /**
5128 * Returns information about the proxy a certain network is using. If given a null network, it
5129 * it will return the proxy for the bound network for the caller app or the default proxy if
5130 * none.
5131 *
5132 * @param network the network we want to get the proxy information for.
5133 * @return Proxy information if a network has a proxy configured, or otherwise null.
5134 */
5135 @Override
5136 public ProxyInfo getProxyForNetwork(Network network) {
5137 final ProxyInfo globalProxy = mProxyTracker.getGlobalProxy();
5138 if (globalProxy != null) return globalProxy;
5139 if (network == null) {
5140 // Get the network associated with the calling UID.
5141 final Network activeNetwork = getActiveNetworkForUidInternal(mDeps.getCallingUid(),
5142 true);
5143 if (activeNetwork == null) {
5144 return null;
5145 }
5146 return getLinkPropertiesProxyInfo(activeNetwork);
5147 } else if (mDeps.queryUserAccess(mDeps.getCallingUid(), network, this)) {
5148 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
5149 // caller may not have.
5150 return getLinkPropertiesProxyInfo(network);
5151 }
5152 // No proxy info available if the calling UID does not have network access.
5153 return null;
5154 }
5155
5156
5157 private ProxyInfo getLinkPropertiesProxyInfo(Network network) {
5158 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5159 if (nai == null) return null;
5160 synchronized (nai) {
5161 final ProxyInfo linkHttpProxy = nai.linkProperties.getHttpProxy();
5162 return linkHttpProxy == null ? null : new ProxyInfo(linkHttpProxy);
5163 }
5164 }
5165
5166 @Override
5167 public void setGlobalProxy(@Nullable final ProxyInfo proxyProperties) {
5168 PermissionUtils.enforceNetworkStackPermission(mContext);
5169 mProxyTracker.setGlobalProxy(proxyProperties);
5170 }
5171
5172 @Override
5173 @Nullable
5174 public ProxyInfo getGlobalProxy() {
5175 return mProxyTracker.getGlobalProxy();
5176 }
5177
5178 private void handleApplyDefaultProxy(ProxyInfo proxy) {
5179 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
5180 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
5181 proxy = null;
5182 }
5183 mProxyTracker.setDefaultProxy(proxy);
5184 }
5185
5186 // If the proxy has changed from oldLp to newLp, resend proxy broadcast. This method gets called
5187 // when any network changes proxy.
5188 // TODO: Remove usage of broadcast extras as they are deprecated and not applicable in a
5189 // multi-network world where an app might be bound to a non-default network.
5190 private void updateProxy(LinkProperties newLp, LinkProperties oldLp) {
5191 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
5192 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
5193
5194 if (!ProxyTracker.proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
5195 mProxyTracker.sendProxyBroadcast();
5196 }
5197 }
5198
5199 private static class SettingsObserver extends ContentObserver {
5200 final private HashMap<Uri, Integer> mUriEventMap;
5201 final private Context mContext;
5202 final private Handler mHandler;
5203
5204 SettingsObserver(Context context, Handler handler) {
5205 super(null);
5206 mUriEventMap = new HashMap<>();
5207 mContext = context;
5208 mHandler = handler;
5209 }
5210
5211 void observe(Uri uri, int what) {
5212 mUriEventMap.put(uri, what);
5213 final ContentResolver resolver = mContext.getContentResolver();
5214 resolver.registerContentObserver(uri, false, this);
5215 }
5216
5217 @Override
5218 public void onChange(boolean selfChange) {
5219 Log.wtf(TAG, "Should never be reached.");
5220 }
5221
5222 @Override
5223 public void onChange(boolean selfChange, Uri uri) {
5224 final Integer what = mUriEventMap.get(uri);
5225 if (what != null) {
5226 mHandler.obtainMessage(what).sendToTarget();
5227 } else {
5228 loge("No matching event to send for URI=" + uri);
5229 }
5230 }
5231 }
5232
5233 private static void log(String s) {
5234 Log.d(TAG, s);
5235 }
5236
5237 private static void logw(String s) {
5238 Log.w(TAG, s);
5239 }
5240
5241 private static void logwtf(String s) {
5242 Log.wtf(TAG, s);
5243 }
5244
5245 private static void logwtf(String s, Throwable t) {
5246 Log.wtf(TAG, s, t);
5247 }
5248
5249 private static void loge(String s) {
5250 Log.e(TAG, s);
5251 }
5252
5253 private static void loge(String s, Throwable t) {
5254 Log.e(TAG, s, t);
5255 }
5256
5257 /**
5258 * Return the information of all ongoing VPNs.
5259 *
5260 * <p>This method is used to update NetworkStatsService.
5261 *
5262 * <p>Must be called on the handler thread.
5263 */
5264 private UnderlyingNetworkInfo[] getAllVpnInfo() {
5265 ensureRunningOnConnectivityServiceThread();
5266 if (mLockdownEnabled) {
5267 return new UnderlyingNetworkInfo[0];
5268 }
5269 List<UnderlyingNetworkInfo> infoList = new ArrayList<>();
5270 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
5271 UnderlyingNetworkInfo info = createVpnInfo(nai);
5272 if (info != null) {
5273 infoList.add(info);
5274 }
5275 }
5276 return infoList.toArray(new UnderlyingNetworkInfo[infoList.size()]);
5277 }
5278
5279 /**
5280 * @return VPN information for accounting, or null if we can't retrieve all required
5281 * information, e.g underlying ifaces.
5282 */
5283 private UnderlyingNetworkInfo createVpnInfo(NetworkAgentInfo nai) {
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00005284 Network[] underlyingNetworks = nai.declaredUnderlyingNetworks;
5285 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
5286 // the underlyingNetworks list.
Treehugger Robot4703a8c2021-07-02 13:55:33 +00005287 // TODO: stop using propagateUnderlyingCapabilities here, for example, by always
5288 // initializing NetworkAgentInfo#declaredUnderlyingNetworks to an empty array.
5289 if (underlyingNetworks == null && nai.propagateUnderlyingCapabilities()) {
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00005290 final NetworkAgentInfo defaultNai = getDefaultNetworkForUid(
5291 nai.networkCapabilities.getOwnerUid());
5292 if (defaultNai != null) {
5293 underlyingNetworks = new Network[] { defaultNai.network };
5294 }
5295 }
5296
5297 if (CollectionUtils.isEmpty(underlyingNetworks)) return null;
5298
5299 List<String> interfaces = new ArrayList<>();
5300 for (Network network : underlyingNetworks) {
5301 NetworkAgentInfo underlyingNai = getNetworkAgentInfoForNetwork(network);
5302 if (underlyingNai == null) continue;
5303 LinkProperties lp = underlyingNai.linkProperties;
5304 for (String iface : lp.getAllInterfaceNames()) {
5305 if (!TextUtils.isEmpty(iface)) {
5306 interfaces.add(iface);
5307 }
5308 }
5309 }
5310
5311 if (interfaces.isEmpty()) return null;
5312
5313 // Must be non-null or NetworkStatsService will crash.
5314 // Cannot happen in production code because Vpn only registers the NetworkAgent after the
5315 // tun or ipsec interface is created.
5316 // TODO: Remove this check.
5317 if (nai.linkProperties.getInterfaceName() == null) return null;
5318
5319 return new UnderlyingNetworkInfo(nai.networkCapabilities.getOwnerUid(),
5320 nai.linkProperties.getInterfaceName(), interfaces);
5321 }
5322
5323 // TODO This needs to be the default network that applies to the NAI.
5324 private Network[] underlyingNetworksOrDefault(final int ownerUid,
5325 Network[] underlyingNetworks) {
5326 final Network defaultNetwork = getNetwork(getDefaultNetworkForUid(ownerUid));
5327 if (underlyingNetworks == null && defaultNetwork != null) {
5328 // null underlying networks means to track the default.
5329 underlyingNetworks = new Network[] { defaultNetwork };
5330 }
5331 return underlyingNetworks;
5332 }
5333
5334 // Returns true iff |network| is an underlying network of |nai|.
5335 private boolean hasUnderlyingNetwork(NetworkAgentInfo nai, Network network) {
5336 // TODO: support more than one level of underlying networks, either via a fixed-depth search
5337 // (e.g., 2 levels of underlying networks), or via loop detection, or....
Treehugger Robot4703a8c2021-07-02 13:55:33 +00005338 if (!nai.propagateUnderlyingCapabilities()) return false;
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00005339 final Network[] underlying = underlyingNetworksOrDefault(
5340 nai.networkCapabilities.getOwnerUid(), nai.declaredUnderlyingNetworks);
5341 return CollectionUtils.contains(underlying, network);
5342 }
5343
5344 /**
5345 * Recompute the capabilities for any networks that had a specific network as underlying.
5346 *
5347 * When underlying networks change, such networks may have to update capabilities to reflect
5348 * things like the metered bit, their transports, and so on. The capabilities are calculated
5349 * immediately. This method runs on the ConnectivityService thread.
5350 */
5351 private void propagateUnderlyingNetworkCapabilities(Network updatedNetwork) {
5352 ensureRunningOnConnectivityServiceThread();
5353 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
5354 if (updatedNetwork == null || hasUnderlyingNetwork(nai, updatedNetwork)) {
5355 updateCapabilitiesForNetwork(nai);
5356 }
5357 }
5358 }
5359
5360 private boolean isUidBlockedByVpn(int uid, List<UidRange> blockedUidRanges) {
5361 // Determine whether this UID is blocked because of always-on VPN lockdown. If a VPN applies
5362 // to the UID, then the UID is not blocked because always-on VPN lockdown applies only when
5363 // a VPN is not up.
5364 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
5365 if (vpnNai != null && !vpnNai.networkAgentConfig.allowBypass) return false;
5366 for (UidRange range : blockedUidRanges) {
5367 if (range.contains(uid)) return true;
5368 }
5369 return false;
5370 }
5371
5372 @Override
5373 public void setRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
5374 enforceNetworkStackOrSettingsPermission();
5375 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_REQUIRE_VPN_FOR_UIDS,
5376 encodeBool(requireVpn), 0 /* arg2 */, ranges));
5377 }
5378
5379 private void handleSetRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
5380 if (DBG) {
5381 Log.d(TAG, "Setting VPN " + (requireVpn ? "" : "not ") + "required for UIDs: "
5382 + Arrays.toString(ranges));
5383 }
5384 // Cannot use a Set since the list of UID ranges might contain duplicates.
5385 final List<UidRange> newVpnBlockedUidRanges = new ArrayList(mVpnBlockedUidRanges);
5386 for (int i = 0; i < ranges.length; i++) {
5387 if (requireVpn) {
5388 newVpnBlockedUidRanges.add(ranges[i]);
5389 } else {
5390 newVpnBlockedUidRanges.remove(ranges[i]);
5391 }
5392 }
5393
5394 try {
5395 mNetd.networkRejectNonSecureVpn(requireVpn, toUidRangeStableParcels(ranges));
5396 } catch (RemoteException | ServiceSpecificException e) {
5397 Log.e(TAG, "setRequireVpnForUids(" + requireVpn + ", "
5398 + Arrays.toString(ranges) + "): netd command failed: " + e);
5399 }
5400
5401 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
5402 final boolean curMetered = nai.networkCapabilities.isMetered();
5403 maybeNotifyNetworkBlocked(nai, curMetered, curMetered,
5404 mVpnBlockedUidRanges, newVpnBlockedUidRanges);
5405 }
5406
5407 mVpnBlockedUidRanges = newVpnBlockedUidRanges;
5408 }
5409
5410 @Override
5411 public void setLegacyLockdownVpnEnabled(boolean enabled) {
5412 enforceNetworkStackOrSettingsPermission();
5413 mHandler.post(() -> mLockdownEnabled = enabled);
5414 }
5415
5416 private boolean isLegacyLockdownNai(NetworkAgentInfo nai) {
5417 return mLockdownEnabled
5418 && getVpnType(nai) == VpnManager.TYPE_VPN_LEGACY
5419 && nai.networkCapabilities.appliesToUid(Process.FIRST_APPLICATION_UID);
5420 }
5421
5422 private NetworkAgentInfo getLegacyLockdownNai() {
5423 if (!mLockdownEnabled) {
5424 return null;
5425 }
5426 // The legacy lockdown VPN always only applies to userId 0.
5427 final NetworkAgentInfo nai = getVpnForUid(Process.FIRST_APPLICATION_UID);
5428 if (nai == null || !isLegacyLockdownNai(nai)) return null;
5429
5430 // The legacy lockdown VPN must always have exactly one underlying network.
5431 // This code may run on any thread and declaredUnderlyingNetworks may change, so store it in
5432 // a local variable. There is no need to make a copy because its contents cannot change.
5433 final Network[] underlying = nai.declaredUnderlyingNetworks;
5434 if (underlying == null || underlying.length != 1) {
5435 return null;
5436 }
5437
5438 // The legacy lockdown VPN always uses the default network.
5439 // If the VPN's underlying network is no longer the current default network, it means that
5440 // the default network has just switched, and the VPN is about to disconnect.
5441 // Report that the VPN is not connected, so the state of NetworkInfo objects overwritten
5442 // by filterForLegacyLockdown will be set to CONNECTING and not CONNECTED.
5443 final NetworkAgentInfo defaultNetwork = getDefaultNetwork();
5444 if (defaultNetwork == null || !defaultNetwork.network.equals(underlying[0])) {
5445 return null;
5446 }
5447
5448 return nai;
5449 };
5450
5451 // TODO: move all callers to filterForLegacyLockdown and delete this method.
5452 // This likely requires making sendLegacyNetworkBroadcast take a NetworkInfo object instead of
5453 // just a DetailedState object.
5454 private DetailedState getLegacyLockdownState(DetailedState origState) {
5455 if (origState != DetailedState.CONNECTED) {
5456 return origState;
5457 }
5458 return (mLockdownEnabled && getLegacyLockdownNai() == null)
5459 ? DetailedState.CONNECTING
5460 : DetailedState.CONNECTED;
5461 }
5462
5463 private void filterForLegacyLockdown(NetworkInfo ni) {
5464 if (!mLockdownEnabled || !ni.isConnected()) return;
5465 // The legacy lockdown VPN replaces the state of every network in CONNECTED state with the
5466 // state of its VPN. This is to ensure that when an underlying network connects, apps will
5467 // not see a CONNECTIVITY_ACTION broadcast for a network in state CONNECTED until the VPN
5468 // comes up, at which point there is a new CONNECTIVITY_ACTION broadcast for the underlying
5469 // network, this time with a state of CONNECTED.
5470 //
5471 // Now that the legacy lockdown code lives in ConnectivityService, and no longer has access
5472 // to the internal state of the Vpn object, always replace the state with CONNECTING. This
5473 // is not too far off the truth, since an always-on VPN, when not connected, is always
5474 // trying to reconnect.
5475 if (getLegacyLockdownNai() == null) {
5476 ni.setDetailedState(DetailedState.CONNECTING, "", null);
5477 }
5478 }
5479
5480 @Override
5481 public void setProvisioningNotificationVisible(boolean visible, int networkType,
5482 String action) {
5483 enforceSettingsPermission();
5484 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
5485 return;
5486 }
5487 final long ident = Binder.clearCallingIdentity();
5488 try {
5489 // Concatenate the range of types onto the range of NetIDs.
5490 int id = NetIdManager.MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
5491 mNotifier.setProvNotificationVisible(visible, id, action);
5492 } finally {
5493 Binder.restoreCallingIdentity(ident);
5494 }
5495 }
5496
5497 @Override
5498 public void setAirplaneMode(boolean enable) {
5499 enforceAirplaneModePermission();
5500 final long ident = Binder.clearCallingIdentity();
5501 try {
5502 final ContentResolver cr = mContext.getContentResolver();
5503 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
5504 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
5505 intent.putExtra("state", enable);
5506 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
5507 } finally {
5508 Binder.restoreCallingIdentity(ident);
5509 }
5510 }
5511
5512 private void onUserAdded(@NonNull final UserHandle user) {
5513 mPermissionMonitor.onUserAdded(user);
5514 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
5515 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
5516 }
5517 }
5518
5519 private void onUserRemoved(@NonNull final UserHandle user) {
5520 mPermissionMonitor.onUserRemoved(user);
5521 // If there was a network preference for this user, remove it.
5522 handleSetProfileNetworkPreference(new ProfileNetworkPreferences.Preference(user, null),
5523 null /* listener */);
5524 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
5525 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
5526 }
5527 }
5528
5529 private void onPackageChanged(@NonNull final String packageName) {
5530 // This is necessary in case a package is added or removed, but also when it's replaced to
5531 // run as a new UID by its manifest rules. Also, if a separate package shares the same UID
5532 // as one in the preferences, then it should follow the same routing as that other package,
5533 // which means updating the rules is never to be needed in this case (whether it joins or
5534 // leaves a UID with a preference).
5535 if (isMappedInOemNetworkPreference(packageName)) {
5536 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
5537 }
5538 }
5539
5540 private final BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
5541 @Override
5542 public void onReceive(Context context, Intent intent) {
5543 ensureRunningOnConnectivityServiceThread();
5544 final String action = intent.getAction();
5545 final UserHandle user = intent.getParcelableExtra(Intent.EXTRA_USER);
5546
5547 // User should be filled for below intents, check the existence.
5548 if (user == null) {
5549 Log.wtf(TAG, intent.getAction() + " broadcast without EXTRA_USER");
5550 return;
5551 }
5552
5553 if (Intent.ACTION_USER_ADDED.equals(action)) {
5554 onUserAdded(user);
5555 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
5556 onUserRemoved(user);
5557 } else {
5558 Log.wtf(TAG, "received unexpected intent: " + action);
5559 }
5560 }
5561 };
5562
5563 private final BroadcastReceiver mPackageIntentReceiver = new BroadcastReceiver() {
5564 @Override
5565 public void onReceive(Context context, Intent intent) {
5566 ensureRunningOnConnectivityServiceThread();
5567 switch (intent.getAction()) {
5568 case Intent.ACTION_PACKAGE_ADDED:
5569 case Intent.ACTION_PACKAGE_REMOVED:
5570 case Intent.ACTION_PACKAGE_REPLACED:
5571 onPackageChanged(intent.getData().getSchemeSpecificPart());
5572 break;
5573 default:
5574 Log.wtf(TAG, "received unexpected intent: " + intent.getAction());
5575 }
5576 }
5577 };
5578
5579 private final HashMap<Messenger, NetworkProviderInfo> mNetworkProviderInfos = new HashMap<>();
5580 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests = new HashMap<>();
5581
5582 private static class NetworkProviderInfo {
5583 public final String name;
5584 public final Messenger messenger;
5585 private final IBinder.DeathRecipient mDeathRecipient;
5586 public final int providerId;
5587
5588 NetworkProviderInfo(String name, Messenger messenger, int providerId,
5589 @NonNull IBinder.DeathRecipient deathRecipient) {
5590 this.name = name;
5591 this.messenger = messenger;
5592 this.providerId = providerId;
5593 mDeathRecipient = deathRecipient;
5594
5595 if (mDeathRecipient == null) {
5596 throw new AssertionError("Must pass a deathRecipient");
5597 }
5598 }
5599
5600 void connect(Context context, Handler handler) {
5601 try {
5602 messenger.getBinder().linkToDeath(mDeathRecipient, 0);
5603 } catch (RemoteException e) {
5604 mDeathRecipient.binderDied();
5605 }
5606 }
5607 }
5608
5609 private void ensureAllNetworkRequestsHaveType(List<NetworkRequest> requests) {
5610 for (int i = 0; i < requests.size(); i++) {
5611 ensureNetworkRequestHasType(requests.get(i));
5612 }
5613 }
5614
5615 private void ensureNetworkRequestHasType(NetworkRequest request) {
5616 if (request.type == NetworkRequest.Type.NONE) {
5617 throw new IllegalArgumentException(
5618 "All NetworkRequests in ConnectivityService must have a type");
5619 }
5620 }
5621
5622 /**
5623 * Tracks info about the requester.
5624 * Also used to notice when the calling process dies so as to self-expire
5625 */
5626 @VisibleForTesting
5627 protected class NetworkRequestInfo implements IBinder.DeathRecipient {
5628 // The requests to be satisfied in priority order. Non-multilayer requests will only have a
5629 // single NetworkRequest in mRequests.
5630 final List<NetworkRequest> mRequests;
5631
5632 // mSatisfier and mActiveRequest rely on one another therefore set them together.
5633 void setSatisfier(
5634 @Nullable final NetworkAgentInfo satisfier,
5635 @Nullable final NetworkRequest activeRequest) {
5636 mSatisfier = satisfier;
5637 mActiveRequest = activeRequest;
5638 }
5639
5640 // The network currently satisfying this NRI. Only one request in an NRI can have a
5641 // satisfier. For non-multilayer requests, only non-listen requests can have a satisfier.
5642 @Nullable
5643 private NetworkAgentInfo mSatisfier;
5644 NetworkAgentInfo getSatisfier() {
5645 return mSatisfier;
5646 }
5647
5648 // The request in mRequests assigned to a network agent. This is null if none of the
5649 // requests in mRequests can be satisfied. This member has the constraint of only being
5650 // accessible on the handler thread.
5651 @Nullable
5652 private NetworkRequest mActiveRequest;
5653 NetworkRequest getActiveRequest() {
5654 return mActiveRequest;
5655 }
5656
5657 final PendingIntent mPendingIntent;
5658 boolean mPendingIntentSent;
5659 @Nullable
5660 final Messenger mMessenger;
5661
5662 // Information about the caller that caused this object to be created.
5663 @Nullable
5664 private final IBinder mBinder;
5665 final int mPid;
5666 final int mUid;
5667 final @NetworkCallback.Flag int mCallbackFlags;
5668 @Nullable
5669 final String mCallingAttributionTag;
5670
5671 // Counter keeping track of this NRI.
5672 final PerUidCounter mPerUidCounter;
5673
5674 // Effective UID of this request. This is different from mUid when a privileged process
5675 // files a request on behalf of another UID. This UID is used to determine blocked status,
5676 // UID matching, and so on. mUid above is used for permission checks and to enforce the
5677 // maximum limit of registered callbacks per UID.
5678 final int mAsUid;
5679
paulhuc2198772021-05-26 15:19:20 +08005680 // Default network priority of this request.
5681 private final int mDefaultNetworkPriority;
5682
5683 int getDefaultNetworkPriority() {
5684 return mDefaultNetworkPriority;
5685 }
5686
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00005687 // In order to preserve the mapping of NetworkRequest-to-callback when apps register
5688 // callbacks using a returned NetworkRequest, the original NetworkRequest needs to be
5689 // maintained for keying off of. This is only a concern when the original nri
5690 // mNetworkRequests changes which happens currently for apps that register callbacks to
5691 // track the default network. In those cases, the nri is updated to have mNetworkRequests
5692 // that match the per-app default nri that currently tracks the calling app's uid so that
5693 // callbacks are fired at the appropriate time. When the callbacks fire,
5694 // mNetworkRequestForCallback will be used so as to preserve the caller's mapping. When
5695 // callbacks are updated to key off of an nri vs NetworkRequest, this stops being an issue.
5696 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
5697 @NonNull
5698 private final NetworkRequest mNetworkRequestForCallback;
5699 NetworkRequest getNetworkRequestForCallback() {
5700 return mNetworkRequestForCallback;
5701 }
5702
5703 /**
5704 * Get the list of UIDs this nri applies to.
5705 */
5706 @NonNull
paulhu71ad4f12021-05-25 14:56:27 +08005707 Set<UidRange> getUids() {
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00005708 // networkCapabilities.getUids() returns a defensive copy.
5709 // multilayer requests will all have the same uids so return the first one.
5710 final Set<UidRange> uids = mRequests.get(0).networkCapabilities.getUidRanges();
5711 return (null == uids) ? new ArraySet<>() : uids;
5712 }
5713
5714 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r,
5715 @Nullable final PendingIntent pi, @Nullable String callingAttributionTag) {
paulhuc2198772021-05-26 15:19:20 +08005716 this(asUid, Collections.singletonList(r), r, pi, callingAttributionTag,
5717 DEFAULT_NETWORK_PRIORITY_NONE);
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00005718 }
5719
5720 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
5721 @NonNull final NetworkRequest requestForCallback, @Nullable final PendingIntent pi,
paulhuc2198772021-05-26 15:19:20 +08005722 @Nullable String callingAttributionTag, final int defaultNetworkPriority) {
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00005723 ensureAllNetworkRequestsHaveType(r);
5724 mRequests = initializeRequests(r);
5725 mNetworkRequestForCallback = requestForCallback;
5726 mPendingIntent = pi;
5727 mMessenger = null;
5728 mBinder = null;
5729 mPid = getCallingPid();
5730 mUid = mDeps.getCallingUid();
5731 mAsUid = asUid;
5732 mPerUidCounter = getRequestCounter(this);
5733 mPerUidCounter.incrementCountOrThrow(mUid);
5734 /**
5735 * Location sensitive data not included in pending intent. Only included in
5736 * {@link NetworkCallback}.
5737 */
5738 mCallbackFlags = NetworkCallback.FLAG_NONE;
5739 mCallingAttributionTag = callingAttributionTag;
paulhuc2198772021-05-26 15:19:20 +08005740 mDefaultNetworkPriority = defaultNetworkPriority;
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00005741 }
5742
5743 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r, @Nullable final Messenger m,
5744 @Nullable final IBinder binder,
5745 @NetworkCallback.Flag int callbackFlags,
5746 @Nullable String callingAttributionTag) {
5747 this(asUid, Collections.singletonList(r), r, m, binder, callbackFlags,
5748 callingAttributionTag);
5749 }
5750
5751 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
5752 @NonNull final NetworkRequest requestForCallback, @Nullable final Messenger m,
5753 @Nullable final IBinder binder,
5754 @NetworkCallback.Flag int callbackFlags,
5755 @Nullable String callingAttributionTag) {
5756 super();
5757 ensureAllNetworkRequestsHaveType(r);
5758 mRequests = initializeRequests(r);
5759 mNetworkRequestForCallback = requestForCallback;
5760 mMessenger = m;
5761 mBinder = binder;
5762 mPid = getCallingPid();
5763 mUid = mDeps.getCallingUid();
5764 mAsUid = asUid;
5765 mPendingIntent = null;
5766 mPerUidCounter = getRequestCounter(this);
5767 mPerUidCounter.incrementCountOrThrow(mUid);
5768 mCallbackFlags = callbackFlags;
5769 mCallingAttributionTag = callingAttributionTag;
paulhuc2198772021-05-26 15:19:20 +08005770 mDefaultNetworkPriority = DEFAULT_NETWORK_PRIORITY_NONE;
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00005771 linkDeathRecipient();
5772 }
5773
5774 NetworkRequestInfo(@NonNull final NetworkRequestInfo nri,
5775 @NonNull final List<NetworkRequest> r) {
5776 super();
5777 ensureAllNetworkRequestsHaveType(r);
5778 mRequests = initializeRequests(r);
5779 mNetworkRequestForCallback = nri.getNetworkRequestForCallback();
5780 final NetworkAgentInfo satisfier = nri.getSatisfier();
5781 if (null != satisfier) {
5782 // If the old NRI was satisfied by an NAI, then it may have had an active request.
5783 // The active request is necessary to figure out what callbacks to send, in
5784 // particular then a network updates its capabilities.
5785 // As this code creates a new NRI with a new set of requests, figure out which of
5786 // the list of requests should be the active request. It is always the first
5787 // request of the list that can be satisfied by the satisfier since the order of
5788 // requests is a priority order.
5789 // Note even in the presence of a satisfier there may not be an active request,
5790 // when the satisfier is the no-service network.
5791 NetworkRequest activeRequest = null;
5792 for (final NetworkRequest candidate : r) {
5793 if (candidate.canBeSatisfiedBy(satisfier.networkCapabilities)) {
5794 activeRequest = candidate;
5795 break;
5796 }
5797 }
5798 setSatisfier(satisfier, activeRequest);
5799 }
5800 mMessenger = nri.mMessenger;
5801 mBinder = nri.mBinder;
5802 mPid = nri.mPid;
5803 mUid = nri.mUid;
5804 mAsUid = nri.mAsUid;
5805 mPendingIntent = nri.mPendingIntent;
5806 mPerUidCounter = getRequestCounter(this);
5807 mPerUidCounter.incrementCountOrThrow(mUid);
5808 mCallbackFlags = nri.mCallbackFlags;
5809 mCallingAttributionTag = nri.mCallingAttributionTag;
paulhuc2198772021-05-26 15:19:20 +08005810 mDefaultNetworkPriority = DEFAULT_NETWORK_PRIORITY_NONE;
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00005811 linkDeathRecipient();
5812 }
5813
5814 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r) {
paulhuc2198772021-05-26 15:19:20 +08005815 this(asUid, Collections.singletonList(r), DEFAULT_NETWORK_PRIORITY_NONE);
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00005816 }
5817
paulhuc2198772021-05-26 15:19:20 +08005818 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
5819 final int defaultNetworkPriority) {
5820 this(asUid, r, r.get(0), null /* pi */, null /* callingAttributionTag */,
5821 defaultNetworkPriority);
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00005822 }
5823
5824 // True if this NRI is being satisfied. It also accounts for if the nri has its satisifer
5825 // set to the mNoServiceNetwork in which case mActiveRequest will be null thus returning
5826 // false.
5827 boolean isBeingSatisfied() {
5828 return (null != mSatisfier && null != mActiveRequest);
5829 }
5830
5831 boolean isMultilayerRequest() {
5832 return mRequests.size() > 1;
5833 }
5834
5835 private List<NetworkRequest> initializeRequests(List<NetworkRequest> r) {
5836 // Creating a defensive copy to prevent the sender from modifying the list being
5837 // reflected in the return value of this method.
5838 final List<NetworkRequest> tempRequests = new ArrayList<>(r);
5839 return Collections.unmodifiableList(tempRequests);
5840 }
5841
5842 void decrementRequestCount() {
5843 mPerUidCounter.decrementCount(mUid);
5844 }
5845
5846 void linkDeathRecipient() {
5847 if (null != mBinder) {
5848 try {
5849 mBinder.linkToDeath(this, 0);
5850 } catch (RemoteException e) {
5851 binderDied();
5852 }
5853 }
5854 }
5855
5856 void unlinkDeathRecipient() {
5857 if (null != mBinder) {
5858 mBinder.unlinkToDeath(this, 0);
5859 }
5860 }
5861
5862 @Override
5863 public void binderDied() {
5864 log("ConnectivityService NetworkRequestInfo binderDied(" +
5865 mRequests + ", " + mBinder + ")");
5866 releaseNetworkRequests(mRequests);
5867 }
5868
5869 @Override
5870 public String toString() {
5871 final String asUidString = (mAsUid == mUid) ? "" : " asUid: " + mAsUid;
5872 return "uid/pid:" + mUid + "/" + mPid + asUidString + " activeRequest: "
5873 + (mActiveRequest == null ? null : mActiveRequest.requestId)
5874 + " callbackRequest: "
5875 + mNetworkRequestForCallback.requestId
5876 + " " + mRequests
5877 + (mPendingIntent == null ? "" : " to trigger " + mPendingIntent)
5878 + " callback flags: " + mCallbackFlags;
5879 }
5880 }
5881
5882 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
5883 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
5884 if (badCapability != null) {
5885 throw new IllegalArgumentException("Cannot request network with " + badCapability);
5886 }
5887 }
5888
5889 // This checks that the passed capabilities either do not request a
5890 // specific SSID/SignalStrength, or the calling app has permission to do so.
5891 private void ensureSufficientPermissionsForRequest(NetworkCapabilities nc,
5892 int callerPid, int callerUid, String callerPackageName) {
5893 if (null != nc.getSsid() && !checkSettingsPermission(callerPid, callerUid)) {
5894 throw new SecurityException("Insufficient permissions to request a specific SSID");
5895 }
5896
5897 if (nc.hasSignalStrength()
5898 && !checkNetworkSignalStrengthWakeupPermission(callerPid, callerUid)) {
5899 throw new SecurityException(
5900 "Insufficient permissions to request a specific signal strength");
5901 }
5902 mAppOpsManager.checkPackage(callerUid, callerPackageName);
5903
5904 if (!nc.getSubscriptionIds().isEmpty()) {
5905 enforceNetworkFactoryPermission();
5906 }
5907 }
5908
5909 private int[] getSignalStrengthThresholds(@NonNull final NetworkAgentInfo nai) {
5910 final SortedSet<Integer> thresholds = new TreeSet<>();
5911 synchronized (nai) {
5912 // mNetworkRequests may contain the same value multiple times in case of
5913 // multilayer requests. It won't matter in this case because the thresholds
5914 // will then be the same and be deduplicated as they enter the `thresholds` set.
5915 // TODO : have mNetworkRequests be a Set<NetworkRequestInfo> or the like.
5916 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
5917 for (final NetworkRequest req : nri.mRequests) {
5918 if (req.networkCapabilities.hasSignalStrength()
5919 && nai.satisfiesImmutableCapabilitiesOf(req)) {
5920 thresholds.add(req.networkCapabilities.getSignalStrength());
5921 }
5922 }
5923 }
5924 }
5925 return CollectionUtils.toIntArray(new ArrayList<>(thresholds));
5926 }
5927
5928 private void updateSignalStrengthThresholds(
5929 NetworkAgentInfo nai, String reason, NetworkRequest request) {
5930 final int[] thresholdsArray = getSignalStrengthThresholds(nai);
5931
5932 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
5933 String detail;
5934 if (request != null && request.networkCapabilities.hasSignalStrength()) {
5935 detail = reason + " " + request.networkCapabilities.getSignalStrength();
5936 } else {
5937 detail = reason;
5938 }
5939 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
5940 detail, Arrays.toString(thresholdsArray), nai.toShortString()));
5941 }
5942
5943 nai.onSignalStrengthThresholdsUpdated(thresholdsArray);
5944 }
5945
5946 private void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
5947 if (nc == null) {
5948 return;
5949 }
5950 NetworkSpecifier ns = nc.getNetworkSpecifier();
5951 if (ns == null) {
5952 return;
5953 }
5954 if (ns instanceof MatchAllNetworkSpecifier) {
5955 throw new IllegalArgumentException("A MatchAllNetworkSpecifier is not permitted");
5956 }
5957 }
5958
5959 private void ensureValid(NetworkCapabilities nc) {
5960 ensureValidNetworkSpecifier(nc);
5961 if (nc.isPrivateDnsBroken()) {
5962 throw new IllegalArgumentException("Can't request broken private DNS");
5963 }
5964 }
5965
5966 private boolean isTargetSdkAtleast(int version, int callingUid,
5967 @NonNull String callingPackageName) {
5968 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
5969 final PackageManager pm =
5970 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
5971 try {
5972 final int callingVersion = pm.getTargetSdkVersion(callingPackageName);
5973 if (callingVersion < version) return false;
5974 } catch (PackageManager.NameNotFoundException e) { }
5975 return true;
5976 }
5977
5978 @Override
5979 public NetworkRequest requestNetwork(int asUid, NetworkCapabilities networkCapabilities,
5980 int reqTypeInt, Messenger messenger, int timeoutMs, IBinder binder,
5981 int legacyType, int callbackFlags, @NonNull String callingPackageName,
5982 @Nullable String callingAttributionTag) {
5983 if (legacyType != TYPE_NONE && !checkNetworkStackPermission()) {
5984 if (isTargetSdkAtleast(Build.VERSION_CODES.M, mDeps.getCallingUid(),
5985 callingPackageName)) {
5986 throw new SecurityException("Insufficient permissions to specify legacy type");
5987 }
5988 }
5989 final NetworkCapabilities defaultNc = mDefaultRequest.mRequests.get(0).networkCapabilities;
5990 final int callingUid = mDeps.getCallingUid();
5991 // Privileged callers can track the default network of another UID by passing in a UID.
5992 if (asUid != Process.INVALID_UID) {
5993 enforceSettingsPermission();
5994 } else {
5995 asUid = callingUid;
5996 }
5997 final NetworkRequest.Type reqType;
5998 try {
5999 reqType = NetworkRequest.Type.values()[reqTypeInt];
6000 } catch (ArrayIndexOutOfBoundsException e) {
6001 throw new IllegalArgumentException("Unsupported request type " + reqTypeInt);
6002 }
6003 switch (reqType) {
6004 case TRACK_DEFAULT:
6005 // If the request type is TRACK_DEFAULT, the passed {@code networkCapabilities}
6006 // is unused and will be replaced by ones appropriate for the UID (usually, the
6007 // calling app). This allows callers to keep track of the default network.
6008 networkCapabilities = copyDefaultNetworkCapabilitiesForUid(
6009 defaultNc, asUid, callingUid, callingPackageName);
6010 enforceAccessPermission();
6011 break;
6012 case TRACK_SYSTEM_DEFAULT:
6013 enforceSettingsPermission();
6014 networkCapabilities = new NetworkCapabilities(defaultNc);
6015 break;
6016 case BACKGROUND_REQUEST:
6017 enforceNetworkStackOrSettingsPermission();
6018 // Fall-through since other checks are the same with normal requests.
6019 case REQUEST:
6020 networkCapabilities = new NetworkCapabilities(networkCapabilities);
6021 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
6022 callingAttributionTag);
6023 // TODO: this is incorrect. We mark the request as metered or not depending on
6024 // the state of the app when the request is filed, but we never change the
6025 // request if the app changes network state. http://b/29964605
6026 enforceMeteredApnPolicy(networkCapabilities);
6027 break;
6028 case LISTEN_FOR_BEST:
6029 enforceAccessPermission();
6030 networkCapabilities = new NetworkCapabilities(networkCapabilities);
6031 break;
6032 default:
6033 throw new IllegalArgumentException("Unsupported request type " + reqType);
6034 }
6035 ensureRequestableCapabilities(networkCapabilities);
6036 ensureSufficientPermissionsForRequest(networkCapabilities,
6037 Binder.getCallingPid(), callingUid, callingPackageName);
6038
6039 // Enforce FOREGROUND if the caller does not have permission to use background network.
6040 if (reqType == LISTEN_FOR_BEST) {
6041 restrictBackgroundRequestForCaller(networkCapabilities);
6042 }
6043
6044 // Set the UID range for this request to the single UID of the requester, unless the
6045 // requester has the permission to specify other UIDs.
6046 // This will overwrite any allowed UIDs in the requested capabilities. Though there
6047 // are no visible methods to set the UIDs, an app could use reflection to try and get
6048 // networks for other apps so it's essential that the UIDs are overwritten.
6049 // Also set the requester UID and package name in the request.
6050 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
6051 callingUid, callingPackageName);
6052
6053 if (timeoutMs < 0) {
6054 throw new IllegalArgumentException("Bad timeout specified");
6055 }
6056 ensureValid(networkCapabilities);
6057
6058 final NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
6059 nextNetworkRequestId(), reqType);
6060 final NetworkRequestInfo nri = getNriToRegister(
6061 asUid, networkRequest, messenger, binder, callbackFlags,
6062 callingAttributionTag);
6063 if (DBG) log("requestNetwork for " + nri);
6064
6065 // For TRACK_SYSTEM_DEFAULT callbacks, the capabilities have been modified since they were
6066 // copied from the default request above. (This is necessary to ensure, for example, that
6067 // the callback does not leak sensitive information to unprivileged apps.) Check that the
6068 // changes don't alter request matching.
6069 if (reqType == NetworkRequest.Type.TRACK_SYSTEM_DEFAULT &&
6070 (!networkCapabilities.equalRequestableCapabilities(defaultNc))) {
6071 throw new IllegalStateException(
6072 "TRACK_SYSTEM_DEFAULT capabilities don't match default request: "
6073 + networkCapabilities + " vs. " + defaultNc);
6074 }
6075
6076 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
6077 if (timeoutMs > 0) {
6078 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
6079 nri), timeoutMs);
6080 }
6081 return networkRequest;
6082 }
6083
6084 /**
6085 * Return the nri to be used when registering a network request. Specifically, this is used with
6086 * requests registered to track the default request. If there is currently a per-app default
6087 * tracking the app requestor, then we need to create a version of this nri that mirrors that of
6088 * the tracking per-app default so that callbacks are sent to the app requestor appropriately.
6089 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
6090 * when a privileged caller is tracking the default network for another uid.
6091 * @param nr the network request for the nri.
6092 * @param msgr the messenger for the nri.
6093 * @param binder the binder for the nri.
6094 * @param callingAttributionTag the calling attribution tag for the nri.
6095 * @return the nri to register.
6096 */
6097 private NetworkRequestInfo getNriToRegister(final int asUid, @NonNull final NetworkRequest nr,
6098 @Nullable final Messenger msgr, @Nullable final IBinder binder,
6099 @NetworkCallback.Flag int callbackFlags,
6100 @Nullable String callingAttributionTag) {
6101 final List<NetworkRequest> requests;
6102 if (NetworkRequest.Type.TRACK_DEFAULT == nr.type) {
6103 requests = copyDefaultNetworkRequestsForUid(
6104 asUid, nr.getRequestorUid(), nr.getRequestorPackageName());
6105 } else {
6106 requests = Collections.singletonList(nr);
6107 }
6108 return new NetworkRequestInfo(
6109 asUid, requests, nr, msgr, binder, callbackFlags, callingAttributionTag);
6110 }
6111
6112 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities,
6113 String callingPackageName, String callingAttributionTag) {
6114 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
6115 enforceConnectivityRestrictedNetworksPermission();
6116 } else {
6117 enforceChangePermission(callingPackageName, callingAttributionTag);
6118 }
6119 }
6120
6121 @Override
6122 public boolean requestBandwidthUpdate(Network network) {
6123 enforceAccessPermission();
6124 NetworkAgentInfo nai = null;
6125 if (network == null) {
6126 return false;
6127 }
6128 synchronized (mNetworkForNetId) {
6129 nai = mNetworkForNetId.get(network.getNetId());
6130 }
6131 if (nai != null) {
6132 nai.onBandwidthUpdateRequested();
6133 synchronized (mBandwidthRequests) {
6134 final int uid = mDeps.getCallingUid();
6135 Integer uidReqs = mBandwidthRequests.get(uid);
6136 if (uidReqs == null) {
6137 uidReqs = 0;
6138 }
6139 mBandwidthRequests.put(uid, ++uidReqs);
6140 }
6141 return true;
6142 }
6143 return false;
6144 }
6145
6146 private boolean isSystem(int uid) {
6147 return uid < Process.FIRST_APPLICATION_UID;
6148 }
6149
6150 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
6151 final int uid = mDeps.getCallingUid();
6152 if (isSystem(uid)) {
6153 // Exemption for system uid.
6154 return;
6155 }
6156 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
6157 // Policy already enforced.
6158 return;
6159 }
6160 final long ident = Binder.clearCallingIdentity();
6161 try {
6162 if (mPolicyManager.isUidRestrictedOnMeteredNetworks(uid)) {
6163 // If UID is restricted, don't allow them to bring up metered APNs.
6164 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
6165 }
6166 } finally {
6167 Binder.restoreCallingIdentity(ident);
6168 }
6169 }
6170
6171 @Override
6172 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
6173 PendingIntent operation, @NonNull String callingPackageName,
6174 @Nullable String callingAttributionTag) {
6175 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
6176 final int callingUid = mDeps.getCallingUid();
6177 networkCapabilities = new NetworkCapabilities(networkCapabilities);
6178 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
6179 callingAttributionTag);
6180 enforceMeteredApnPolicy(networkCapabilities);
6181 ensureRequestableCapabilities(networkCapabilities);
6182 ensureSufficientPermissionsForRequest(networkCapabilities,
6183 Binder.getCallingPid(), callingUid, callingPackageName);
6184 ensureValidNetworkSpecifier(networkCapabilities);
6185 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
6186 callingUid, callingPackageName);
6187
6188 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
6189 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
6190 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
6191 callingAttributionTag);
6192 if (DBG) log("pendingRequest for " + nri);
6193 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
6194 nri));
6195 return networkRequest;
6196 }
6197
6198 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
6199 mHandler.sendMessageDelayed(
6200 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
6201 mDeps.getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
6202 }
6203
6204 @Override
6205 public void releasePendingNetworkRequest(PendingIntent operation) {
6206 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
6207 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
6208 mDeps.getCallingUid(), 0, operation));
6209 }
6210
6211 // In order to implement the compatibility measure for pre-M apps that call
6212 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
6213 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
6214 // This ensures it has permission to do so.
6215 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
6216 if (nc == null) {
6217 return false;
6218 }
6219 int[] transportTypes = nc.getTransportTypes();
6220 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
6221 return false;
6222 }
6223 try {
6224 mContext.enforceCallingOrSelfPermission(
6225 android.Manifest.permission.ACCESS_WIFI_STATE,
6226 "ConnectivityService");
6227 } catch (SecurityException e) {
6228 return false;
6229 }
6230 return true;
6231 }
6232
6233 @Override
6234 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
6235 Messenger messenger, IBinder binder,
6236 @NetworkCallback.Flag int callbackFlags,
6237 @NonNull String callingPackageName, @NonNull String callingAttributionTag) {
6238 final int callingUid = mDeps.getCallingUid();
6239 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
6240 enforceAccessPermission();
6241 }
6242
6243 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
6244 ensureSufficientPermissionsForRequest(networkCapabilities,
6245 Binder.getCallingPid(), callingUid, callingPackageName);
6246 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
6247 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
6248 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
6249 // onLost and onAvailable callbacks when networks move in and out of the background.
6250 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
6251 // can't request networks.
6252 restrictBackgroundRequestForCaller(nc);
6253 ensureValid(nc);
6254
6255 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
6256 NetworkRequest.Type.LISTEN);
6257 NetworkRequestInfo nri =
6258 new NetworkRequestInfo(callingUid, networkRequest, messenger, binder, callbackFlags,
6259 callingAttributionTag);
6260 if (VDBG) log("listenForNetwork for " + nri);
6261
6262 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
6263 return networkRequest;
6264 }
6265
6266 @Override
6267 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
6268 PendingIntent operation, @NonNull String callingPackageName,
6269 @Nullable String callingAttributionTag) {
6270 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
6271 final int callingUid = mDeps.getCallingUid();
6272 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
6273 enforceAccessPermission();
6274 }
6275 ensureValid(networkCapabilities);
6276 ensureSufficientPermissionsForRequest(networkCapabilities,
6277 Binder.getCallingPid(), callingUid, callingPackageName);
6278 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
6279 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
6280
6281 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
6282 NetworkRequest.Type.LISTEN);
6283 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
6284 callingAttributionTag);
6285 if (VDBG) log("pendingListenForNetwork for " + nri);
6286
Treehugger Robot282f7432021-06-30 21:59:16 +00006287 mHandler.sendMessage(mHandler.obtainMessage(
6288 EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT, nri));
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00006289 }
6290
6291 /** Returns the next Network provider ID. */
6292 public final int nextNetworkProviderId() {
6293 return mNextNetworkProviderId.getAndIncrement();
6294 }
6295
6296 private void releaseNetworkRequests(List<NetworkRequest> networkRequests) {
6297 for (int i = 0; i < networkRequests.size(); i++) {
6298 releaseNetworkRequest(networkRequests.get(i));
6299 }
6300 }
6301
6302 @Override
6303 public void releaseNetworkRequest(NetworkRequest networkRequest) {
6304 ensureNetworkRequestHasType(networkRequest);
6305 mHandler.sendMessage(mHandler.obtainMessage(
6306 EVENT_RELEASE_NETWORK_REQUEST, mDeps.getCallingUid(), 0, networkRequest));
6307 }
6308
6309 private void handleRegisterNetworkProvider(NetworkProviderInfo npi) {
6310 if (mNetworkProviderInfos.containsKey(npi.messenger)) {
6311 // Avoid creating duplicates. even if an app makes a direct AIDL call.
6312 // This will never happen if an app calls ConnectivityManager#registerNetworkProvider,
6313 // as that will throw if a duplicate provider is registered.
6314 loge("Attempt to register existing NetworkProviderInfo "
6315 + mNetworkProviderInfos.get(npi.messenger).name);
6316 return;
6317 }
6318
6319 if (DBG) log("Got NetworkProvider Messenger for " + npi.name);
6320 mNetworkProviderInfos.put(npi.messenger, npi);
6321 npi.connect(mContext, mTrackerHandler);
6322 }
6323
6324 @Override
6325 public int registerNetworkProvider(Messenger messenger, String name) {
6326 enforceNetworkFactoryOrSettingsPermission();
6327 Objects.requireNonNull(messenger, "messenger must be non-null");
6328 NetworkProviderInfo npi = new NetworkProviderInfo(name, messenger,
6329 nextNetworkProviderId(), () -> unregisterNetworkProvider(messenger));
6330 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_PROVIDER, npi));
6331 return npi.providerId;
6332 }
6333
6334 @Override
6335 public void unregisterNetworkProvider(Messenger messenger) {
6336 enforceNetworkFactoryOrSettingsPermission();
6337 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_PROVIDER, messenger));
6338 }
6339
6340 @Override
6341 public void offerNetwork(final int providerId,
6342 @NonNull final NetworkScore score, @NonNull final NetworkCapabilities caps,
6343 @NonNull final INetworkOfferCallback callback) {
6344 Objects.requireNonNull(score);
6345 Objects.requireNonNull(caps);
6346 Objects.requireNonNull(callback);
6347 final NetworkOffer offer = new NetworkOffer(
6348 FullScore.makeProspectiveScore(score, caps), caps, callback, providerId);
6349 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_OFFER, offer));
6350 }
6351
6352 @Override
6353 public void unofferNetwork(@NonNull final INetworkOfferCallback callback) {
6354 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_OFFER, callback));
6355 }
6356
6357 private void handleUnregisterNetworkProvider(Messenger messenger) {
6358 NetworkProviderInfo npi = mNetworkProviderInfos.remove(messenger);
6359 if (npi == null) {
6360 loge("Failed to find Messenger in unregisterNetworkProvider");
6361 return;
6362 }
6363 // Unregister all the offers from this provider
6364 final ArrayList<NetworkOfferInfo> toRemove = new ArrayList<>();
6365 for (final NetworkOfferInfo noi : mNetworkOffers) {
6366 if (noi.offer.providerId == npi.providerId) {
6367 // Can't call handleUnregisterNetworkOffer here because iteration is in progress
6368 toRemove.add(noi);
6369 }
6370 }
6371 for (final NetworkOfferInfo noi : toRemove) {
6372 handleUnregisterNetworkOffer(noi);
6373 }
6374 if (DBG) log("unregisterNetworkProvider for " + npi.name);
6375 }
6376
6377 @Override
6378 public void declareNetworkRequestUnfulfillable(@NonNull final NetworkRequest request) {
6379 if (request.hasTransport(TRANSPORT_TEST)) {
6380 enforceNetworkFactoryOrTestNetworksPermission();
6381 } else {
6382 enforceNetworkFactoryPermission();
6383 }
6384 final NetworkRequestInfo nri = mNetworkRequests.get(request);
6385 if (nri != null) {
6386 // declareNetworkRequestUnfulfillable() paths don't apply to multilayer requests.
6387 ensureNotMultilayerRequest(nri, "declareNetworkRequestUnfulfillable");
6388 mHandler.post(() -> handleReleaseNetworkRequest(
6389 nri.mRequests.get(0), mDeps.getCallingUid(), true));
6390 }
6391 }
6392
6393 // NOTE: Accessed on multiple threads, must be synchronized on itself.
6394 @GuardedBy("mNetworkForNetId")
6395 private final SparseArray<NetworkAgentInfo> mNetworkForNetId = new SparseArray<>();
6396 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
6397 // An entry is first reserved with NetIdManager, prior to being added to mNetworkForNetId, so
6398 // there may not be a strict 1:1 correlation between the two.
6399 private final NetIdManager mNetIdManager;
6400
Lorenzo Colittibeb7d922021-06-09 08:33:36 +00006401 // Tracks all NetworkAgents that are currently registered.
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00006402 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
6403 private final ArraySet<NetworkAgentInfo> mNetworkAgentInfos = new ArraySet<>();
6404
6405 // UID ranges for users that are currently blocked by VPNs.
6406 // This array is accessed and iterated on multiple threads without holding locks, so its
6407 // contents must never be mutated. When the ranges change, the array is replaced with a new one
6408 // (on the handler thread).
6409 private volatile List<UidRange> mVpnBlockedUidRanges = new ArrayList<>();
6410
6411 // Must only be accessed on the handler thread
6412 @NonNull
6413 private final ArrayList<NetworkOfferInfo> mNetworkOffers = new ArrayList<>();
6414
6415 @GuardedBy("mBlockedAppUids")
6416 private final HashSet<Integer> mBlockedAppUids = new HashSet<>();
6417
6418 // Current OEM network preferences. This object must only be written to on the handler thread.
6419 // Since it is immutable and always non-null, other threads may read it if they only care
6420 // about seeing a consistent object but not that it is current.
6421 @NonNull
6422 private OemNetworkPreferences mOemNetworkPreferences =
6423 new OemNetworkPreferences.Builder().build();
6424 // Current per-profile network preferences. This object follows the same threading rules as
6425 // the OEM network preferences above.
6426 @NonNull
6427 private ProfileNetworkPreferences mProfileNetworkPreferences = new ProfileNetworkPreferences();
6428
paulhu71ad4f12021-05-25 14:56:27 +08006429 // A set of UIDs that should use mobile data preferentially if available. This object follows
6430 // the same threading rules as the OEM network preferences above.
6431 @NonNull
6432 private Set<Integer> mMobileDataPreferredUids = new ArraySet<>();
6433
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00006434 // OemNetworkPreferences activity String log entries.
6435 private static final int MAX_OEM_NETWORK_PREFERENCE_LOGS = 20;
6436 @NonNull
6437 private final LocalLog mOemNetworkPreferencesLogs =
6438 new LocalLog(MAX_OEM_NETWORK_PREFERENCE_LOGS);
6439
6440 /**
6441 * Determine whether a given package has a mapping in the current OemNetworkPreferences.
6442 * @param packageName the package name to check existence of a mapping for.
6443 * @return true if a mapping exists, false otherwise
6444 */
6445 private boolean isMappedInOemNetworkPreference(@NonNull final String packageName) {
6446 return mOemNetworkPreferences.getNetworkPreferences().containsKey(packageName);
6447 }
6448
6449 // The always-on request for an Internet-capable network that apps without a specific default
6450 // fall back to.
6451 @VisibleForTesting
6452 @NonNull
6453 final NetworkRequestInfo mDefaultRequest;
6454 // Collection of NetworkRequestInfo's used for default networks.
6455 @VisibleForTesting
6456 @NonNull
6457 final ArraySet<NetworkRequestInfo> mDefaultNetworkRequests = new ArraySet<>();
6458
6459 private boolean isPerAppDefaultRequest(@NonNull final NetworkRequestInfo nri) {
6460 return (mDefaultNetworkRequests.contains(nri) && mDefaultRequest != nri);
6461 }
6462
6463 /**
6464 * Return the default network request currently tracking the given uid.
6465 * @param uid the uid to check.
6466 * @return the NetworkRequestInfo tracking the given uid.
6467 */
6468 @NonNull
6469 private NetworkRequestInfo getDefaultRequestTrackingUid(final int uid) {
6470 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
6471 if (nri == mDefaultRequest) {
6472 continue;
6473 }
6474 // Checking the first request is sufficient as only multilayer requests will have more
6475 // than one request and for multilayer, all requests will track the same uids.
6476 if (nri.mRequests.get(0).networkCapabilities.appliesToUid(uid)) {
6477 return nri;
6478 }
6479 }
6480 return mDefaultRequest;
6481 }
6482
6483 /**
6484 * Get a copy of the network requests of the default request that is currently tracking the
6485 * given uid.
6486 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
6487 * when a privileged caller is tracking the default network for another uid.
6488 * @param requestorUid the uid to check the default for.
6489 * @param requestorPackageName the requestor's package name.
6490 * @return a copy of the default's NetworkRequest that is tracking the given uid.
6491 */
6492 @NonNull
6493 private List<NetworkRequest> copyDefaultNetworkRequestsForUid(
6494 final int asUid, final int requestorUid, @NonNull final String requestorPackageName) {
6495 return copyNetworkRequestsForUid(
6496 getDefaultRequestTrackingUid(asUid).mRequests,
6497 asUid, requestorUid, requestorPackageName);
6498 }
6499
6500 /**
6501 * Copy the given nri's NetworkRequest collection.
6502 * @param requestsToCopy the NetworkRequest collection to be copied.
6503 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
6504 * when a privileged caller is tracking the default network for another uid.
6505 * @param requestorUid the uid to set on the copied collection.
6506 * @param requestorPackageName the package name to set on the copied collection.
6507 * @return the copied NetworkRequest collection.
6508 */
6509 @NonNull
6510 private List<NetworkRequest> copyNetworkRequestsForUid(
6511 @NonNull final List<NetworkRequest> requestsToCopy, final int asUid,
6512 final int requestorUid, @NonNull final String requestorPackageName) {
6513 final List<NetworkRequest> requests = new ArrayList<>();
6514 for (final NetworkRequest nr : requestsToCopy) {
6515 requests.add(new NetworkRequest(copyDefaultNetworkCapabilitiesForUid(
6516 nr.networkCapabilities, asUid, requestorUid, requestorPackageName),
6517 nr.legacyType, nextNetworkRequestId(), nr.type));
6518 }
6519 return requests;
6520 }
6521
6522 @NonNull
6523 private NetworkCapabilities copyDefaultNetworkCapabilitiesForUid(
6524 @NonNull final NetworkCapabilities netCapToCopy, final int asUid,
6525 final int requestorUid, @NonNull final String requestorPackageName) {
6526 // These capabilities are for a TRACK_DEFAULT callback, so:
6527 // 1. Remove NET_CAPABILITY_VPN, because it's (currently!) the only difference between
6528 // mDefaultRequest and a per-UID default request.
6529 // TODO: stop depending on the fact that these two unrelated things happen to be the same
6530 // 2. Always set the UIDs to asUid. restrictRequestUidsForCallerAndSetRequestorInfo will
6531 // not do this in the case of a privileged application.
6532 final NetworkCapabilities netCap = new NetworkCapabilities(netCapToCopy);
6533 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
6534 netCap.setSingleUid(asUid);
6535 restrictRequestUidsForCallerAndSetRequestorInfo(
6536 netCap, requestorUid, requestorPackageName);
6537 return netCap;
6538 }
6539
6540 /**
6541 * Get the nri that is currently being tracked for callbacks by per-app defaults.
6542 * @param nr the network request to check for equality against.
6543 * @return the nri if one exists, null otherwise.
6544 */
6545 @Nullable
6546 private NetworkRequestInfo getNriForAppRequest(@NonNull final NetworkRequest nr) {
6547 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
6548 if (nri.getNetworkRequestForCallback().equals(nr)) {
6549 return nri;
6550 }
6551 }
6552 return null;
6553 }
6554
6555 /**
6556 * Check if an nri is currently being managed by per-app default networking.
6557 * @param nri the nri to check.
6558 * @return true if this nri is currently being managed by per-app default networking.
6559 */
6560 private boolean isPerAppTrackedNri(@NonNull final NetworkRequestInfo nri) {
6561 // nri.mRequests.get(0) is only different from the original request filed in
6562 // nri.getNetworkRequestForCallback() if nri.mRequests was changed by per-app default
6563 // functionality therefore if these two don't match, it means this particular nri is
6564 // currently being managed by a per-app default.
6565 return nri.getNetworkRequestForCallback() != nri.mRequests.get(0);
6566 }
6567
6568 /**
6569 * Determine if an nri is a managed default request that disallows default networking.
6570 * @param nri the request to evaluate
6571 * @return true if device-default networking is disallowed
6572 */
6573 private boolean isDefaultBlocked(@NonNull final NetworkRequestInfo nri) {
6574 // Check if this nri is a managed default that supports the default network at its
6575 // lowest priority request.
6576 final NetworkRequest defaultNetworkRequest = mDefaultRequest.mRequests.get(0);
6577 final NetworkCapabilities lowestPriorityNetCap =
6578 nri.mRequests.get(nri.mRequests.size() - 1).networkCapabilities;
6579 return isPerAppDefaultRequest(nri)
6580 && !(defaultNetworkRequest.networkCapabilities.equalRequestableCapabilities(
6581 lowestPriorityNetCap));
6582 }
6583
6584 // Request used to optionally keep mobile data active even when higher
6585 // priority networks like Wi-Fi are active.
6586 private final NetworkRequest mDefaultMobileDataRequest;
6587
6588 // Request used to optionally keep wifi data active even when higher
6589 // priority networks like ethernet are active.
6590 private final NetworkRequest mDefaultWifiRequest;
6591
6592 // Request used to optionally keep vehicle internal network always active
6593 private final NetworkRequest mDefaultVehicleRequest;
6594
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00006595 // Sentinel NAI used to direct apps with default networks that should have no connectivity to a
6596 // network with no service. This NAI should never be matched against, nor should any public API
6597 // ever return the associated network. For this reason, this NAI is not in the list of available
6598 // NAIs. It is used in computeNetworkReassignment() to be set as the satisfier for non-device
6599 // default requests that don't support using the device default network which will ultimately
6600 // allow ConnectivityService to use this no-service network when calling makeDefaultForApps().
6601 @VisibleForTesting
6602 final NetworkAgentInfo mNoServiceNetwork;
6603
6604 // The NetworkAgentInfo currently satisfying the default request, if any.
6605 private NetworkAgentInfo getDefaultNetwork() {
6606 return mDefaultRequest.mSatisfier;
6607 }
6608
6609 private NetworkAgentInfo getDefaultNetworkForUid(final int uid) {
6610 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
6611 // Currently, all network requests will have the same uids therefore checking the first
6612 // one is sufficient. If/when uids are tracked at the nri level, this can change.
6613 final Set<UidRange> uids = nri.mRequests.get(0).networkCapabilities.getUidRanges();
6614 if (null == uids) {
6615 continue;
6616 }
6617 for (final UidRange range : uids) {
6618 if (range.contains(uid)) {
6619 return nri.getSatisfier();
6620 }
6621 }
6622 }
6623 return getDefaultNetwork();
6624 }
6625
6626 @Nullable
6627 private Network getNetwork(@Nullable NetworkAgentInfo nai) {
6628 return nai != null ? nai.network : null;
6629 }
6630
6631 private void ensureRunningOnConnectivityServiceThread() {
6632 if (mHandler.getLooper().getThread() != Thread.currentThread()) {
6633 throw new IllegalStateException(
6634 "Not running on ConnectivityService thread: "
6635 + Thread.currentThread().getName());
6636 }
6637 }
6638
6639 @VisibleForTesting
6640 protected boolean isDefaultNetwork(NetworkAgentInfo nai) {
6641 return nai == getDefaultNetwork();
6642 }
6643
6644 /**
6645 * Register a new agent with ConnectivityService to handle a network.
6646 *
6647 * @param na a reference for ConnectivityService to contact the agent asynchronously.
6648 * @param networkInfo the initial info associated with this network. It can be updated later :
6649 * see {@link #updateNetworkInfo}.
6650 * @param linkProperties the initial link properties of this network. They can be updated
6651 * later : see {@link #updateLinkProperties}.
6652 * @param networkCapabilities the initial capabilites of this network. They can be updated
6653 * later : see {@link #updateCapabilities}.
6654 * @param initialScore the initial score of the network. See
6655 * {@link NetworkAgentInfo#getCurrentScore}.
6656 * @param networkAgentConfig metadata about the network. This is never updated.
6657 * @param providerId the ID of the provider owning this NetworkAgent.
6658 * @return the network created for this agent.
6659 */
6660 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo networkInfo,
6661 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
6662 @NonNull NetworkScore initialScore, NetworkAgentConfig networkAgentConfig,
6663 int providerId) {
6664 Objects.requireNonNull(networkInfo, "networkInfo must not be null");
6665 Objects.requireNonNull(linkProperties, "linkProperties must not be null");
6666 Objects.requireNonNull(networkCapabilities, "networkCapabilities must not be null");
6667 Objects.requireNonNull(initialScore, "initialScore must not be null");
6668 Objects.requireNonNull(networkAgentConfig, "networkAgentConfig must not be null");
6669 if (networkCapabilities.hasTransport(TRANSPORT_TEST)) {
6670 enforceAnyPermissionOf(Manifest.permission.MANAGE_TEST_NETWORKS);
6671 } else {
6672 enforceNetworkFactoryPermission();
6673 }
6674
6675 final int uid = mDeps.getCallingUid();
6676 final long token = Binder.clearCallingIdentity();
6677 try {
6678 return registerNetworkAgentInternal(na, networkInfo, linkProperties,
6679 networkCapabilities, initialScore, networkAgentConfig, providerId, uid);
6680 } finally {
6681 Binder.restoreCallingIdentity(token);
6682 }
6683 }
6684
6685 private Network registerNetworkAgentInternal(INetworkAgent na, NetworkInfo networkInfo,
6686 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
6687 NetworkScore currentScore, NetworkAgentConfig networkAgentConfig, int providerId,
6688 int uid) {
6689 if (networkCapabilities.hasTransport(TRANSPORT_TEST)) {
6690 // Strictly, sanitizing here is unnecessary as the capabilities will be sanitized in
6691 // the call to mixInCapabilities below anyway, but sanitizing here means the NAI never
6692 // sees capabilities that may be malicious, which might prevent mistakes in the future.
6693 networkCapabilities = new NetworkCapabilities(networkCapabilities);
6694 networkCapabilities.restrictCapabilitesForTestNetwork(uid);
6695 }
6696
6697 LinkProperties lp = new LinkProperties(linkProperties);
6698
6699 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
6700 final NetworkAgentInfo nai = new NetworkAgentInfo(na,
6701 new Network(mNetIdManager.reserveNetId()), new NetworkInfo(networkInfo), lp, nc,
6702 currentScore, mContext, mTrackerHandler, new NetworkAgentConfig(networkAgentConfig),
6703 this, mNetd, mDnsResolver, providerId, uid, mLingerDelayMs,
6704 mQosCallbackTracker, mDeps);
6705
6706 // Make sure the LinkProperties and NetworkCapabilities reflect what the agent info says.
6707 processCapabilitiesFromAgent(nai, nc);
6708 nai.getAndSetNetworkCapabilities(mixInCapabilities(nai, nc));
6709 processLinkPropertiesFromAgent(nai, nai.linkProperties);
6710
6711 final String extraInfo = networkInfo.getExtraInfo();
6712 final String name = TextUtils.isEmpty(extraInfo)
6713 ? nai.networkCapabilities.getSsid() : extraInfo;
6714 if (DBG) log("registerNetworkAgent " + nai);
6715 mDeps.getNetworkStack().makeNetworkMonitor(
6716 nai.network, name, new NetworkMonitorCallbacks(nai));
6717 // NetworkAgentInfo registration will finish when the NetworkMonitor is created.
6718 // If the network disconnects or sends any other event before that, messages are deferred by
6719 // NetworkAgent until nai.connect(), which will be called when finalizing the
6720 // registration.
6721 return nai.network;
6722 }
6723
6724 private void handleRegisterNetworkAgent(NetworkAgentInfo nai, INetworkMonitor networkMonitor) {
6725 nai.onNetworkMonitorCreated(networkMonitor);
6726 if (VDBG) log("Got NetworkAgent Messenger");
6727 mNetworkAgentInfos.add(nai);
6728 synchronized (mNetworkForNetId) {
6729 mNetworkForNetId.put(nai.network.getNetId(), nai);
6730 }
6731
6732 try {
6733 networkMonitor.start();
6734 } catch (RemoteException e) {
6735 e.rethrowAsRuntimeException();
6736 }
6737 nai.notifyRegistered();
6738 NetworkInfo networkInfo = nai.networkInfo;
6739 updateNetworkInfo(nai, networkInfo);
6740 updateUids(nai, null, nai.networkCapabilities);
6741 }
6742
6743 private class NetworkOfferInfo implements IBinder.DeathRecipient {
6744 @NonNull public final NetworkOffer offer;
6745
6746 NetworkOfferInfo(@NonNull final NetworkOffer offer) {
6747 this.offer = offer;
6748 }
6749
6750 @Override
6751 public void binderDied() {
6752 mHandler.post(() -> handleUnregisterNetworkOffer(this));
6753 }
6754 }
6755
6756 private boolean isNetworkProviderWithIdRegistered(final int providerId) {
6757 for (final NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
6758 if (npi.providerId == providerId) return true;
6759 }
6760 return false;
6761 }
6762
6763 /**
6764 * Register or update a network offer.
6765 * @param newOffer The new offer. If the callback member is the same as an existing
6766 * offer, it is an update of that offer.
6767 */
6768 private void handleRegisterNetworkOffer(@NonNull final NetworkOffer newOffer) {
6769 ensureRunningOnConnectivityServiceThread();
6770 if (!isNetworkProviderWithIdRegistered(newOffer.providerId)) {
6771 // This may actually happen if a provider updates its score or registers and then
6772 // immediately unregisters. The offer would still be in the handler queue, but the
6773 // provider would have been removed.
6774 if (DBG) log("Received offer from an unregistered provider");
6775 return;
6776 }
6777 final NetworkOfferInfo existingOffer = findNetworkOfferInfoByCallback(newOffer.callback);
6778 if (null != existingOffer) {
6779 handleUnregisterNetworkOffer(existingOffer);
6780 newOffer.migrateFrom(existingOffer.offer);
6781 }
6782 final NetworkOfferInfo noi = new NetworkOfferInfo(newOffer);
6783 try {
6784 noi.offer.callback.asBinder().linkToDeath(noi, 0 /* flags */);
6785 } catch (RemoteException e) {
6786 noi.binderDied();
6787 return;
6788 }
6789 mNetworkOffers.add(noi);
6790 issueNetworkNeeds(noi);
6791 }
6792
6793 private void handleUnregisterNetworkOffer(@NonNull final NetworkOfferInfo noi) {
6794 ensureRunningOnConnectivityServiceThread();
6795 mNetworkOffers.remove(noi);
6796 noi.offer.callback.asBinder().unlinkToDeath(noi, 0 /* flags */);
6797 }
6798
6799 @Nullable private NetworkOfferInfo findNetworkOfferInfoByCallback(
6800 @NonNull final INetworkOfferCallback callback) {
6801 ensureRunningOnConnectivityServiceThread();
6802 for (final NetworkOfferInfo noi : mNetworkOffers) {
6803 if (noi.offer.callback.asBinder().equals(callback.asBinder())) return noi;
6804 }
6805 return null;
6806 }
6807
6808 /**
6809 * Called when receiving LinkProperties directly from a NetworkAgent.
6810 * Stores into |nai| any data coming from the agent that might also be written to the network's
6811 * LinkProperties by ConnectivityService itself. This ensures that the data provided by the
6812 * agent is not lost when updateLinkProperties is called.
6813 * This method should never alter the agent's LinkProperties, only store data in |nai|.
6814 */
6815 private void processLinkPropertiesFromAgent(NetworkAgentInfo nai, LinkProperties lp) {
6816 lp.ensureDirectlyConnectedRoutes();
6817 nai.clatd.setNat64PrefixFromRa(lp.getNat64Prefix());
6818 nai.networkAgentPortalData = lp.getCaptivePortalData();
6819 }
6820
6821 private void updateLinkProperties(NetworkAgentInfo networkAgent, @NonNull LinkProperties newLp,
6822 @NonNull LinkProperties oldLp) {
6823 int netId = networkAgent.network.getNetId();
6824
6825 // The NetworkAgent does not know whether clatd is running on its network or not, or whether
6826 // a NAT64 prefix was discovered by the DNS resolver. Before we do anything else, make sure
6827 // the LinkProperties for the network are accurate.
6828 networkAgent.clatd.fixupLinkProperties(oldLp, newLp);
6829
6830 updateInterfaces(newLp, oldLp, netId, networkAgent.networkCapabilities);
6831
6832 // update filtering rules, need to happen after the interface update so netd knows about the
6833 // new interface (the interface name -> index map becomes initialized)
6834 updateVpnFiltering(newLp, oldLp, networkAgent);
6835
6836 updateMtu(newLp, oldLp);
6837 // TODO - figure out what to do for clat
6838// for (LinkProperties lp : newLp.getStackedLinks()) {
6839// updateMtu(lp, null);
6840// }
6841 if (isDefaultNetwork(networkAgent)) {
6842 updateTcpBufferSizes(newLp.getTcpBufferSizes());
6843 }
6844
6845 updateRoutes(newLp, oldLp, netId);
6846 updateDnses(newLp, oldLp, netId);
6847 // Make sure LinkProperties represents the latest private DNS status.
6848 // This does not need to be done before updateDnses because the
6849 // LinkProperties are not the source of the private DNS configuration.
6850 // updateDnses will fetch the private DNS configuration from DnsManager.
6851 mDnsManager.updatePrivateDnsStatus(netId, newLp);
6852
6853 if (isDefaultNetwork(networkAgent)) {
6854 handleApplyDefaultProxy(newLp.getHttpProxy());
6855 } else {
6856 updateProxy(newLp, oldLp);
6857 }
6858
6859 updateWakeOnLan(newLp);
6860
6861 // Captive portal data is obtained from NetworkMonitor and stored in NetworkAgentInfo.
6862 // It is not always contained in the LinkProperties sent from NetworkAgents, and if it
6863 // does, it needs to be merged here.
6864 newLp.setCaptivePortalData(mergeCaptivePortalData(networkAgent.networkAgentPortalData,
6865 networkAgent.capportApiData));
6866
6867 // TODO - move this check to cover the whole function
6868 if (!Objects.equals(newLp, oldLp)) {
6869 synchronized (networkAgent) {
6870 networkAgent.linkProperties = newLp;
6871 }
6872 // Start or stop DNS64 detection and 464xlat according to network state.
6873 networkAgent.clatd.update();
6874 notifyIfacesChangedForNetworkStats();
6875 networkAgent.networkMonitor().notifyLinkPropertiesChanged(
6876 new LinkProperties(newLp, true /* parcelSensitiveFields */));
6877 if (networkAgent.everConnected) {
6878 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
6879 }
6880 }
6881
6882 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
6883 }
6884
6885 /**
6886 * @param naData captive portal data from NetworkAgent
6887 * @param apiData captive portal data from capport API
6888 */
6889 @Nullable
6890 private CaptivePortalData mergeCaptivePortalData(CaptivePortalData naData,
6891 CaptivePortalData apiData) {
6892 if (naData == null || apiData == null) {
6893 return naData == null ? apiData : naData;
6894 }
6895 final CaptivePortalData.Builder captivePortalBuilder =
6896 new CaptivePortalData.Builder(naData);
6897
6898 if (apiData.isCaptive()) {
6899 captivePortalBuilder.setCaptive(true);
6900 }
6901 if (apiData.isSessionExtendable()) {
6902 captivePortalBuilder.setSessionExtendable(true);
6903 }
6904 if (apiData.getExpiryTimeMillis() >= 0 || apiData.getByteLimit() >= 0) {
6905 // Expiry time, bytes remaining, refresh time all need to come from the same source,
6906 // otherwise data would be inconsistent. Prefer the capport API info if present,
6907 // as it can generally be refreshed more often.
6908 captivePortalBuilder.setExpiryTime(apiData.getExpiryTimeMillis());
6909 captivePortalBuilder.setBytesRemaining(apiData.getByteLimit());
6910 captivePortalBuilder.setRefreshTime(apiData.getRefreshTimeMillis());
6911 } else if (naData.getExpiryTimeMillis() < 0 && naData.getByteLimit() < 0) {
6912 // No source has time / bytes remaining information: surface the newest refresh time
6913 // for other fields
6914 captivePortalBuilder.setRefreshTime(
6915 Math.max(naData.getRefreshTimeMillis(), apiData.getRefreshTimeMillis()));
6916 }
6917
6918 // Prioritize the user portal URL from the network agent if the source is authenticated.
6919 if (apiData.getUserPortalUrl() != null && naData.getUserPortalUrlSource()
6920 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
6921 captivePortalBuilder.setUserPortalUrl(apiData.getUserPortalUrl(),
6922 apiData.getUserPortalUrlSource());
6923 }
6924 // Prioritize the venue information URL from the network agent if the source is
6925 // authenticated.
6926 if (apiData.getVenueInfoUrl() != null && naData.getVenueInfoUrlSource()
6927 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
6928 captivePortalBuilder.setVenueInfoUrl(apiData.getVenueInfoUrl(),
6929 apiData.getVenueInfoUrlSource());
6930 }
6931 return captivePortalBuilder.build();
6932 }
6933
6934 private void wakeupModifyInterface(String iface, NetworkCapabilities caps, boolean add) {
6935 // Marks are only available on WiFi interfaces. Checking for
6936 // marks on unsupported interfaces is harmless.
6937 if (!caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
6938 return;
6939 }
6940
6941 int mark = mResources.get().getInteger(R.integer.config_networkWakeupPacketMark);
6942 int mask = mResources.get().getInteger(R.integer.config_networkWakeupPacketMask);
6943
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00006944 // Mask/mark of zero will not detect anything interesting.
6945 // Don't install rules unless both values are nonzero.
6946 if (mark == 0 || mask == 0) {
6947 return;
6948 }
6949
6950 final String prefix = "iface:" + iface;
6951 try {
6952 if (add) {
6953 mNetd.wakeupAddInterface(iface, prefix, mark, mask);
6954 } else {
6955 mNetd.wakeupDelInterface(iface, prefix, mark, mask);
6956 }
6957 } catch (Exception e) {
6958 loge("Exception modifying wakeup packet monitoring: " + e);
6959 }
6960
6961 }
6962
6963 private void updateInterfaces(final @Nullable LinkProperties newLp,
6964 final @Nullable LinkProperties oldLp, final int netId,
6965 final @NonNull NetworkCapabilities caps) {
6966 final CompareResult<String> interfaceDiff = new CompareResult<>(
6967 oldLp != null ? oldLp.getAllInterfaceNames() : null,
6968 newLp != null ? newLp.getAllInterfaceNames() : null);
6969 if (!interfaceDiff.added.isEmpty()) {
6970 for (final String iface : interfaceDiff.added) {
6971 try {
6972 if (DBG) log("Adding iface " + iface + " to network " + netId);
6973 mNetd.networkAddInterface(netId, iface);
6974 wakeupModifyInterface(iface, caps, true);
6975 mDeps.reportNetworkInterfaceForTransports(mContext, iface,
6976 caps.getTransportTypes());
6977 } catch (Exception e) {
6978 logw("Exception adding interface: " + e);
6979 }
6980 }
6981 }
6982 for (final String iface : interfaceDiff.removed) {
6983 try {
6984 if (DBG) log("Removing iface " + iface + " from network " + netId);
6985 wakeupModifyInterface(iface, caps, false);
6986 mNetd.networkRemoveInterface(netId, iface);
6987 } catch (Exception e) {
6988 loge("Exception removing interface: " + e);
6989 }
6990 }
6991 }
6992
6993 // TODO: move to frameworks/libs/net.
6994 private RouteInfoParcel convertRouteInfo(RouteInfo route) {
6995 final String nextHop;
6996
6997 switch (route.getType()) {
6998 case RouteInfo.RTN_UNICAST:
6999 if (route.hasGateway()) {
7000 nextHop = route.getGateway().getHostAddress();
7001 } else {
7002 nextHop = INetd.NEXTHOP_NONE;
7003 }
7004 break;
7005 case RouteInfo.RTN_UNREACHABLE:
7006 nextHop = INetd.NEXTHOP_UNREACHABLE;
7007 break;
7008 case RouteInfo.RTN_THROW:
7009 nextHop = INetd.NEXTHOP_THROW;
7010 break;
7011 default:
7012 nextHop = INetd.NEXTHOP_NONE;
7013 break;
7014 }
7015
7016 final RouteInfoParcel rip = new RouteInfoParcel();
7017 rip.ifName = route.getInterface();
7018 rip.destination = route.getDestination().toString();
7019 rip.nextHop = nextHop;
7020 rip.mtu = route.getMtu();
7021
7022 return rip;
7023 }
7024
7025 /**
7026 * Have netd update routes from oldLp to newLp.
7027 * @return true if routes changed between oldLp and newLp
7028 */
7029 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
7030 // compare the route diff to determine which routes have been updated
7031 final CompareOrUpdateResult<RouteInfo.RouteKey, RouteInfo> routeDiff =
7032 new CompareOrUpdateResult<>(
7033 oldLp != null ? oldLp.getAllRoutes() : null,
7034 newLp != null ? newLp.getAllRoutes() : null,
7035 (r) -> r.getRouteKey());
7036
7037 // add routes before removing old in case it helps with continuous connectivity
7038
7039 // do this twice, adding non-next-hop routes first, then routes they are dependent on
7040 for (RouteInfo route : routeDiff.added) {
7041 if (route.hasGateway()) continue;
7042 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
7043 try {
7044 mNetd.networkAddRouteParcel(netId, convertRouteInfo(route));
7045 } catch (Exception e) {
7046 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
7047 loge("Exception in networkAddRouteParcel for non-gateway: " + e);
7048 }
7049 }
7050 }
7051 for (RouteInfo route : routeDiff.added) {
7052 if (!route.hasGateway()) continue;
7053 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
7054 try {
7055 mNetd.networkAddRouteParcel(netId, convertRouteInfo(route));
7056 } catch (Exception e) {
7057 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
7058 loge("Exception in networkAddRouteParcel for gateway: " + e);
7059 }
7060 }
7061 }
7062
7063 for (RouteInfo route : routeDiff.removed) {
7064 if (VDBG || DDBG) log("Removing Route [" + route + "] from network " + netId);
7065 try {
7066 mNetd.networkRemoveRouteParcel(netId, convertRouteInfo(route));
7067 } catch (Exception e) {
7068 loge("Exception in networkRemoveRouteParcel: " + e);
7069 }
7070 }
7071
7072 for (RouteInfo route : routeDiff.updated) {
7073 if (VDBG || DDBG) log("Updating Route [" + route + "] from network " + netId);
7074 try {
7075 mNetd.networkUpdateRouteParcel(netId, convertRouteInfo(route));
7076 } catch (Exception e) {
7077 loge("Exception in networkUpdateRouteParcel: " + e);
7078 }
7079 }
7080 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty()
7081 || !routeDiff.updated.isEmpty();
7082 }
7083
7084 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
7085 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
7086 return; // no updating necessary
7087 }
7088
7089 if (DBG) {
7090 final Collection<InetAddress> dnses = newLp.getDnsServers();
7091 log("Setting DNS servers for network " + netId + " to " + dnses);
7092 }
7093 try {
7094 mDnsManager.noteDnsServersForNetwork(netId, newLp);
7095 mDnsManager.flushVmDnsCache();
7096 } catch (Exception e) {
7097 loge("Exception in setDnsConfigurationForNetwork: " + e);
7098 }
7099 }
7100
7101 private void updateVpnFiltering(LinkProperties newLp, LinkProperties oldLp,
7102 NetworkAgentInfo nai) {
7103 final String oldIface = oldLp != null ? oldLp.getInterfaceName() : null;
7104 final String newIface = newLp != null ? newLp.getInterfaceName() : null;
7105 final boolean wasFiltering = requiresVpnIsolation(nai, nai.networkCapabilities, oldLp);
7106 final boolean needsFiltering = requiresVpnIsolation(nai, nai.networkCapabilities, newLp);
7107
7108 if (!wasFiltering && !needsFiltering) {
7109 // Nothing to do.
7110 return;
7111 }
7112
7113 if (Objects.equals(oldIface, newIface) && (wasFiltering == needsFiltering)) {
7114 // Nothing changed.
7115 return;
7116 }
7117
7118 final Set<UidRange> ranges = nai.networkCapabilities.getUidRanges();
7119 final int vpnAppUid = nai.networkCapabilities.getOwnerUid();
7120 // TODO: this create a window of opportunity for apps to receive traffic between the time
7121 // when the old rules are removed and the time when new rules are added. To fix this,
7122 // make eBPF support two allowlisted interfaces so here new rules can be added before the
7123 // old rules are being removed.
7124 if (wasFiltering) {
7125 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, ranges, vpnAppUid);
7126 }
7127 if (needsFiltering) {
7128 mPermissionMonitor.onVpnUidRangesAdded(newIface, ranges, vpnAppUid);
7129 }
7130 }
7131
7132 private void updateWakeOnLan(@NonNull LinkProperties lp) {
7133 if (mWolSupportedInterfaces == null) {
7134 mWolSupportedInterfaces = new ArraySet<>(mResources.get().getStringArray(
7135 R.array.config_wakeonlan_supported_interfaces));
7136 }
7137 lp.setWakeOnLanSupported(mWolSupportedInterfaces.contains(lp.getInterfaceName()));
7138 }
7139
7140 private int getNetworkPermission(NetworkCapabilities nc) {
7141 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
7142 return INetd.PERMISSION_SYSTEM;
7143 }
7144 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
7145 return INetd.PERMISSION_NETWORK;
7146 }
7147 return INetd.PERMISSION_NONE;
7148 }
7149
7150 private void updateNetworkPermissions(@NonNull final NetworkAgentInfo nai,
7151 @NonNull final NetworkCapabilities newNc) {
7152 final int oldPermission = getNetworkPermission(nai.networkCapabilities);
7153 final int newPermission = getNetworkPermission(newNc);
7154 if (oldPermission != newPermission && nai.created && !nai.isVPN()) {
7155 try {
7156 mNetd.networkSetPermissionForNetwork(nai.network.getNetId(), newPermission);
7157 } catch (RemoteException | ServiceSpecificException e) {
7158 loge("Exception in networkSetPermissionForNetwork: " + e);
7159 }
7160 }
7161 }
7162
7163 /**
7164 * Called when receiving NetworkCapabilities directly from a NetworkAgent.
7165 * Stores into |nai| any data coming from the agent that might also be written to the network's
7166 * NetworkCapabilities by ConnectivityService itself. This ensures that the data provided by the
7167 * agent is not lost when updateCapabilities is called.
7168 * This method should never alter the agent's NetworkCapabilities, only store data in |nai|.
7169 */
7170 private void processCapabilitiesFromAgent(NetworkAgentInfo nai, NetworkCapabilities nc) {
7171 // Note: resetting the owner UID before storing the agent capabilities in NAI means that if
7172 // the agent attempts to change the owner UID, then nai.declaredCapabilities will not
7173 // actually be the same as the capabilities sent by the agent. Still, it is safer to reset
7174 // the owner UID here and behave as if the agent had never tried to change it.
7175 if (nai.networkCapabilities.getOwnerUid() != nc.getOwnerUid()) {
7176 Log.e(TAG, nai.toShortString() + ": ignoring attempt to change owner from "
7177 + nai.networkCapabilities.getOwnerUid() + " to " + nc.getOwnerUid());
7178 nc.setOwnerUid(nai.networkCapabilities.getOwnerUid());
7179 }
7180 nai.declaredCapabilities = new NetworkCapabilities(nc);
7181 }
7182
7183 /** Modifies |newNc| based on the capabilities of |underlyingNetworks| and |agentCaps|. */
7184 @VisibleForTesting
7185 void applyUnderlyingCapabilities(@Nullable Network[] underlyingNetworks,
7186 @NonNull NetworkCapabilities agentCaps, @NonNull NetworkCapabilities newNc) {
7187 underlyingNetworks = underlyingNetworksOrDefault(
7188 agentCaps.getOwnerUid(), underlyingNetworks);
7189 long transportTypes = NetworkCapabilitiesUtils.packBits(agentCaps.getTransportTypes());
7190 int downKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
7191 int upKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
7192 // metered if any underlying is metered, or originally declared metered by the agent.
7193 boolean metered = !agentCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
7194 boolean roaming = false; // roaming if any underlying is roaming
7195 boolean congested = false; // congested if any underlying is congested
7196 boolean suspended = true; // suspended if all underlying are suspended
7197
7198 boolean hadUnderlyingNetworks = false;
7199 if (null != underlyingNetworks) {
7200 for (Network underlyingNetwork : underlyingNetworks) {
7201 final NetworkAgentInfo underlying =
7202 getNetworkAgentInfoForNetwork(underlyingNetwork);
7203 if (underlying == null) continue;
7204
7205 final NetworkCapabilities underlyingCaps = underlying.networkCapabilities;
7206 hadUnderlyingNetworks = true;
7207 for (int underlyingType : underlyingCaps.getTransportTypes()) {
7208 transportTypes |= 1L << underlyingType;
7209 }
7210
7211 // Merge capabilities of this underlying network. For bandwidth, assume the
7212 // worst case.
7213 downKbps = NetworkCapabilities.minBandwidth(downKbps,
7214 underlyingCaps.getLinkDownstreamBandwidthKbps());
7215 upKbps = NetworkCapabilities.minBandwidth(upKbps,
7216 underlyingCaps.getLinkUpstreamBandwidthKbps());
7217 // If this underlying network is metered, the VPN is metered (it may cost money
7218 // to send packets on this network).
7219 metered |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
7220 // If this underlying network is roaming, the VPN is roaming (the billing structure
7221 // is different than the usual, local one).
7222 roaming |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_ROAMING);
7223 // If this underlying network is congested, the VPN is congested (the current
7224 // condition of the network affects the performance of this network).
7225 congested |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_CONGESTED);
7226 // If this network is not suspended, the VPN is not suspended (the VPN
7227 // is able to transfer some data).
7228 suspended &= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
7229 }
7230 }
7231 if (!hadUnderlyingNetworks) {
7232 // No idea what the underlying networks are; assume reasonable defaults
7233 metered = true;
7234 roaming = false;
7235 congested = false;
7236 suspended = false;
7237 }
7238
7239 newNc.setTransportTypes(NetworkCapabilitiesUtils.unpackBits(transportTypes));
7240 newNc.setLinkDownstreamBandwidthKbps(downKbps);
7241 newNc.setLinkUpstreamBandwidthKbps(upKbps);
7242 newNc.setCapability(NET_CAPABILITY_NOT_METERED, !metered);
7243 newNc.setCapability(NET_CAPABILITY_NOT_ROAMING, !roaming);
7244 newNc.setCapability(NET_CAPABILITY_NOT_CONGESTED, !congested);
7245 newNc.setCapability(NET_CAPABILITY_NOT_SUSPENDED, !suspended);
7246 }
7247
7248 /**
7249 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
7250 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
7251 * and foreground status).
7252 */
7253 @NonNull
7254 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
7255 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
7256 // Don't complain for VPNs since they're not driven by requests and there is no risk of
7257 // causing a connect/teardown loop.
7258 // TODO: remove this altogether and make it the responsibility of the NetworkProviders to
7259 // avoid connect/teardown loops.
7260 if (nai.everConnected &&
7261 !nai.isVPN() &&
7262 !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
7263 // TODO: consider not complaining when a network agent degrades its capabilities if this
7264 // does not cause any request (that is not a listen) currently matching that agent to
7265 // stop being matched by the updated agent.
7266 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
7267 if (!TextUtils.isEmpty(diff)) {
7268 Log.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
7269 }
7270 }
7271
7272 // Don't modify caller's NetworkCapabilities.
7273 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
7274 if (nai.lastValidated) {
7275 newNc.addCapability(NET_CAPABILITY_VALIDATED);
7276 } else {
7277 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
7278 }
7279 if (nai.lastCaptivePortalDetected) {
7280 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
7281 } else {
7282 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
7283 }
7284 if (nai.isBackgroundNetwork()) {
7285 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
7286 } else {
7287 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
7288 }
7289 if (nai.partialConnectivity) {
7290 newNc.addCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
7291 } else {
7292 newNc.removeCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
7293 }
7294 newNc.setPrivateDnsBroken(nai.networkCapabilities.isPrivateDnsBroken());
7295
7296 // TODO : remove this once all factories are updated to send NOT_SUSPENDED and NOT_ROAMING
7297 if (!newNc.hasTransport(TRANSPORT_CELLULAR)) {
7298 newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
7299 newNc.addCapability(NET_CAPABILITY_NOT_ROAMING);
7300 }
7301
Treehugger Robot4703a8c2021-07-02 13:55:33 +00007302 if (nai.propagateUnderlyingCapabilities()) {
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00007303 applyUnderlyingCapabilities(nai.declaredUnderlyingNetworks, nai.declaredCapabilities,
7304 newNc);
7305 }
7306
7307 return newNc;
7308 }
7309
7310 private void updateNetworkInfoForRoamingAndSuspended(NetworkAgentInfo nai,
7311 NetworkCapabilities prevNc, NetworkCapabilities newNc) {
7312 final boolean prevSuspended = !prevNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
7313 final boolean suspended = !newNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
7314 final boolean prevRoaming = !prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
7315 final boolean roaming = !newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
7316 if (prevSuspended != suspended) {
7317 // TODO (b/73132094) : remove this call once the few users of onSuspended and
7318 // onResumed have been removed.
7319 notifyNetworkCallbacks(nai, suspended ? ConnectivityManager.CALLBACK_SUSPENDED
7320 : ConnectivityManager.CALLBACK_RESUMED);
7321 }
7322 if (prevSuspended != suspended || prevRoaming != roaming) {
7323 // updateNetworkInfo will mix in the suspended info from the capabilities and
7324 // take appropriate action for the network having possibly changed state.
7325 updateNetworkInfo(nai, nai.networkInfo);
7326 }
7327 }
7328
7329 /**
7330 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
7331 *
7332 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
7333 * capabilities we manage and store in {@code nai}, such as validated status and captive
7334 * portal status)
7335 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
7336 * potentially triggers rematches.
7337 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
7338 * change.)
7339 *
7340 * @param oldScore score of the network before any of the changes that prompted us
7341 * to call this function.
7342 * @param nai the network having its capabilities updated.
7343 * @param nc the new network capabilities.
7344 */
7345 private void updateCapabilities(final int oldScore, @NonNull final NetworkAgentInfo nai,
7346 @NonNull final NetworkCapabilities nc) {
7347 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
7348 if (Objects.equals(nai.networkCapabilities, newNc)) return;
7349 updateNetworkPermissions(nai, newNc);
7350 final NetworkCapabilities prevNc = nai.getAndSetNetworkCapabilities(newNc);
7351
7352 updateUids(nai, prevNc, newNc);
7353 nai.updateScoreForNetworkAgentUpdate();
7354
7355 if (nai.getCurrentScore() == oldScore && newNc.equalRequestableCapabilities(prevNc)) {
7356 // If the requestable capabilities haven't changed, and the score hasn't changed, then
7357 // the change we're processing can't affect any requests, it can only affect the listens
7358 // on this network. We might have been called by rematchNetworkAndRequests when a
7359 // network changed foreground state.
7360 processListenRequests(nai);
7361 } else {
7362 // If the requestable capabilities have changed or the score changed, we can't have been
7363 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
7364 rematchAllNetworksAndRequests();
7365 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
7366 }
7367 updateNetworkInfoForRoamingAndSuspended(nai, prevNc, newNc);
7368
7369 final boolean oldMetered = prevNc.isMetered();
7370 final boolean newMetered = newNc.isMetered();
7371 final boolean meteredChanged = oldMetered != newMetered;
7372
7373 if (meteredChanged) {
7374 maybeNotifyNetworkBlocked(nai, oldMetered, newMetered,
7375 mVpnBlockedUidRanges, mVpnBlockedUidRanges);
7376 }
7377
7378 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING)
7379 != newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
7380
7381 // Report changes that are interesting for network statistics tracking.
7382 if (meteredChanged || roamingChanged) {
7383 notifyIfacesChangedForNetworkStats();
7384 }
7385
7386 // This network might have been underlying another network. Propagate its capabilities.
7387 propagateUnderlyingNetworkCapabilities(nai.network);
7388
7389 if (!newNc.equalsTransportTypes(prevNc)) {
7390 mDnsManager.updateTransportsForNetwork(
7391 nai.network.getNetId(), newNc.getTransportTypes());
7392 }
Lucas Lin950a65f2021-06-15 09:28:16 +00007393
7394 maybeSendProxyBroadcast(nai, prevNc, newNc);
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00007395 }
7396
7397 /** Convenience method to update the capabilities for a given network. */
7398 private void updateCapabilitiesForNetwork(NetworkAgentInfo nai) {
7399 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
7400 }
7401
7402 /**
7403 * Returns whether VPN isolation (ingress interface filtering) should be applied on the given
7404 * network.
7405 *
7406 * Ingress interface filtering enforces that all apps under the given network can only receive
7407 * packets from the network's interface (and loopback). This is important for VPNs because
7408 * apps that cannot bypass a fully-routed VPN shouldn't be able to receive packets from any
7409 * non-VPN interfaces.
7410 *
7411 * As a result, this method should return true iff
7412 * 1. the network is an app VPN (not legacy VPN)
7413 * 2. the VPN does not allow bypass
7414 * 3. the VPN is fully-routed
7415 * 4. the VPN interface is non-null
7416 *
7417 * @see INetd#firewallAddUidInterfaceRules
7418 * @see INetd#firewallRemoveUidInterfaceRules
7419 */
7420 private boolean requiresVpnIsolation(@NonNull NetworkAgentInfo nai, NetworkCapabilities nc,
7421 LinkProperties lp) {
7422 if (nc == null || lp == null) return false;
7423 return nai.isVPN()
7424 && !nai.networkAgentConfig.allowBypass
7425 && nc.getOwnerUid() != Process.SYSTEM_UID
7426 && lp.getInterfaceName() != null
7427 && (lp.hasIpv4DefaultRoute() || lp.hasIpv4UnreachableDefaultRoute())
7428 && (lp.hasIpv6DefaultRoute() || lp.hasIpv6UnreachableDefaultRoute());
7429 }
7430
7431 private static UidRangeParcel[] toUidRangeStableParcels(final @NonNull Set<UidRange> ranges) {
7432 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.size()];
7433 int index = 0;
7434 for (UidRange range : ranges) {
7435 stableRanges[index] = new UidRangeParcel(range.start, range.stop);
7436 index++;
7437 }
7438 return stableRanges;
7439 }
7440
7441 private static UidRangeParcel[] toUidRangeStableParcels(UidRange[] ranges) {
7442 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.length];
7443 for (int i = 0; i < ranges.length; i++) {
7444 stableRanges[i] = new UidRangeParcel(ranges[i].start, ranges[i].stop);
7445 }
7446 return stableRanges;
7447 }
7448
7449 private void maybeCloseSockets(NetworkAgentInfo nai, UidRangeParcel[] ranges,
7450 int[] exemptUids) {
7451 if (nai.isVPN() && !nai.networkAgentConfig.allowBypass) {
7452 try {
7453 mNetd.socketDestroy(ranges, exemptUids);
7454 } catch (Exception e) {
7455 loge("Exception in socket destroy: ", e);
7456 }
7457 }
7458 }
7459
7460 private void updateUidRanges(boolean add, NetworkAgentInfo nai, Set<UidRange> uidRanges) {
7461 int[] exemptUids = new int[2];
7462 // TODO: Excluding VPN_UID is necessary in order to not to kill the TCP connection used
7463 // by PPTP. Fix this by making Vpn set the owner UID to VPN_UID instead of system when
7464 // starting a legacy VPN, and remove VPN_UID here. (b/176542831)
7465 exemptUids[0] = VPN_UID;
7466 exemptUids[1] = nai.networkCapabilities.getOwnerUid();
7467 UidRangeParcel[] ranges = toUidRangeStableParcels(uidRanges);
7468
7469 maybeCloseSockets(nai, ranges, exemptUids);
7470 try {
7471 if (add) {
paulhude2a2392021-06-09 16:11:35 +08007472 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
7473 nai.network.netId, ranges, DEFAULT_NETWORK_PRIORITY_NONE));
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00007474 } else {
paulhude2a2392021-06-09 16:11:35 +08007475 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
7476 nai.network.netId, ranges, DEFAULT_NETWORK_PRIORITY_NONE));
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00007477 }
7478 } catch (Exception e) {
7479 loge("Exception while " + (add ? "adding" : "removing") + " uid ranges " + uidRanges +
7480 " on netId " + nai.network.netId + ". " + e);
7481 }
7482 maybeCloseSockets(nai, ranges, exemptUids);
7483 }
7484
Lucas Lin950a65f2021-06-15 09:28:16 +00007485 private boolean isProxySetOnAnyDefaultNetwork() {
7486 ensureRunningOnConnectivityServiceThread();
7487 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
7488 final NetworkAgentInfo nai = nri.getSatisfier();
7489 if (nai != null && nai.linkProperties.getHttpProxy() != null) {
7490 return true;
7491 }
7492 }
7493 return false;
7494 }
7495
7496 private void maybeSendProxyBroadcast(NetworkAgentInfo nai, NetworkCapabilities prevNc,
7497 NetworkCapabilities newNc) {
7498 // When the apps moved from/to a VPN, a proxy broadcast is needed to inform the apps that
7499 // the proxy might be changed since the default network satisfied by the apps might also
7500 // changed.
7501 // TODO: Try to track the default network that apps use and only send a proxy broadcast when
7502 // that happens to prevent false alarms.
7503 if (nai.isVPN() && nai.everConnected && !NetworkCapabilities.hasSameUids(prevNc, newNc)
7504 && (nai.linkProperties.getHttpProxy() != null || isProxySetOnAnyDefaultNetwork())) {
7505 mProxyTracker.sendProxyBroadcast();
7506 }
7507 }
7508
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00007509 private void updateUids(NetworkAgentInfo nai, NetworkCapabilities prevNc,
7510 NetworkCapabilities newNc) {
7511 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUidRanges();
7512 Set<UidRange> newRanges = null == newNc ? null : newNc.getUidRanges();
7513 if (null == prevRanges) prevRanges = new ArraySet<>();
7514 if (null == newRanges) newRanges = new ArraySet<>();
7515 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
7516
7517 prevRanges.removeAll(newRanges);
7518 newRanges.removeAll(prevRangesCopy);
7519
7520 try {
7521 // When updating the VPN uid routing rules, add the new range first then remove the old
7522 // range. If old range were removed first, there would be a window between the old
7523 // range being removed and the new range being added, during which UIDs contained
7524 // in both ranges are not subject to any VPN routing rules. Adding new range before
7525 // removing old range works because, unlike the filtering rules below, it's possible to
7526 // add duplicate UID routing rules.
7527 // TODO: calculate the intersection of add & remove. Imagining that we are trying to
7528 // remove uid 3 from a set containing 1-5. Intersection of the prev and new sets is:
7529 // [1-5] & [1-2],[4-5] == [3]
7530 // Then we can do:
7531 // maybeCloseSockets([3])
7532 // mNetd.networkAddUidRanges([1-2],[4-5])
7533 // mNetd.networkRemoveUidRanges([1-5])
7534 // maybeCloseSockets([3])
7535 // This can prevent the sockets of uid 1-2, 4-5 from being closed. It also reduce the
7536 // number of binder calls from 6 to 4.
7537 if (!newRanges.isEmpty()) {
7538 updateUidRanges(true, nai, newRanges);
7539 }
7540 if (!prevRanges.isEmpty()) {
7541 updateUidRanges(false, nai, prevRanges);
7542 }
7543 final boolean wasFiltering = requiresVpnIsolation(nai, prevNc, nai.linkProperties);
7544 final boolean shouldFilter = requiresVpnIsolation(nai, newNc, nai.linkProperties);
7545 final String iface = nai.linkProperties.getInterfaceName();
7546 // For VPN uid interface filtering, old ranges need to be removed before new ranges can
7547 // be added, due to the range being expanded and stored as individual UIDs. For example
7548 // the UIDs might be updated from [0, 99999] to ([0, 10012], [10014, 99999]) which means
7549 // prevRanges = [0, 99999] while newRanges = [0, 10012], [10014, 99999]. If prevRanges
7550 // were added first and then newRanges got removed later, there would be only one uid
7551 // 10013 left. A consequence of removing old ranges before adding new ranges is that
7552 // there is now a window of opportunity when the UIDs are not subject to any filtering.
7553 // Note that this is in contrast with the (more robust) update of VPN routing rules
7554 // above, where the addition of new ranges happens before the removal of old ranges.
7555 // TODO Fix this window by computing an accurate diff on Set<UidRange>, so the old range
7556 // to be removed will never overlap with the new range to be added.
7557 if (wasFiltering && !prevRanges.isEmpty()) {
7558 mPermissionMonitor.onVpnUidRangesRemoved(iface, prevRanges, prevNc.getOwnerUid());
7559 }
7560 if (shouldFilter && !newRanges.isEmpty()) {
7561 mPermissionMonitor.onVpnUidRangesAdded(iface, newRanges, newNc.getOwnerUid());
7562 }
7563 } catch (Exception e) {
7564 // Never crash!
7565 loge("Exception in updateUids: ", e);
7566 }
7567 }
7568
7569 public void handleUpdateLinkProperties(NetworkAgentInfo nai, LinkProperties newLp) {
7570 ensureRunningOnConnectivityServiceThread();
7571
Lorenzo Colittibeb7d922021-06-09 08:33:36 +00007572 if (!mNetworkAgentInfos.contains(nai)) {
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00007573 // Ignore updates for disconnected networks
7574 return;
7575 }
7576 if (VDBG || DDBG) {
7577 log("Update of LinkProperties for " + nai.toShortString()
7578 + "; created=" + nai.created
7579 + "; everConnected=" + nai.everConnected);
7580 }
7581 // TODO: eliminate this defensive copy after confirming that updateLinkProperties does not
7582 // modify its oldLp parameter.
7583 updateLinkProperties(nai, newLp, new LinkProperties(nai.linkProperties));
7584 }
7585
7586 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
7587 int notificationType) {
7588 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
7589 Intent intent = new Intent();
7590 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
7591 // If apps could file multi-layer requests with PendingIntents, they'd need to know
7592 // which of the layer is satisfied alongside with some ID for the request. Hence, if
7593 // such an API is ever implemented, there is no doubt the right request to send in
Remi NGUYEN VAN4cb61892021-06-28 07:27:47 +00007594 // EXTRA_NETWORK_REQUEST is the active request, and whatever ID would be added would
7595 // need to be sent as a separate extra.
7596 final NetworkRequest req = nri.isMultilayerRequest()
7597 ? nri.getActiveRequest()
7598 // Non-multilayer listen requests do not have an active request
7599 : nri.mRequests.get(0);
7600 if (req == null) {
7601 Log.wtf(TAG, "No request in NRI " + nri);
7602 }
7603 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, req);
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00007604 nri.mPendingIntentSent = true;
7605 sendIntent(nri.mPendingIntent, intent);
7606 }
7607 // else not handled
7608 }
7609
7610 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
7611 mPendingIntentWakeLock.acquire();
7612 try {
7613 if (DBG) log("Sending " + pendingIntent);
7614 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
7615 } catch (PendingIntent.CanceledException e) {
7616 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
7617 mPendingIntentWakeLock.release();
7618 releasePendingNetworkRequest(pendingIntent);
7619 }
7620 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
7621 }
7622
7623 @Override
7624 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
7625 String resultData, Bundle resultExtras) {
7626 if (DBG) log("Finished sending " + pendingIntent);
7627 mPendingIntentWakeLock.release();
7628 // Release with a delay so the receiving client has an opportunity to put in its
7629 // own request.
7630 releasePendingNetworkRequestWithDelay(pendingIntent);
7631 }
7632
7633 private void callCallbackForRequest(@NonNull final NetworkRequestInfo nri,
7634 @NonNull final NetworkAgentInfo networkAgent, final int notificationType,
7635 final int arg1) {
7636 if (nri.mMessenger == null) {
7637 // Default request has no msgr. Also prevents callbacks from being invoked for
7638 // NetworkRequestInfos registered with ConnectivityDiagnostics requests. Those callbacks
7639 // are Type.LISTEN, but should not have NetworkCallbacks invoked.
7640 return;
7641 }
7642 Bundle bundle = new Bundle();
7643 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
7644 // TODO: check if defensive copies of data is needed.
7645 final NetworkRequest nrForCallback = nri.getNetworkRequestForCallback();
7646 putParcelable(bundle, nrForCallback);
7647 Message msg = Message.obtain();
7648 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
7649 putParcelable(bundle, networkAgent.network);
7650 }
7651 final boolean includeLocationSensitiveInfo =
7652 (nri.mCallbackFlags & NetworkCallback.FLAG_INCLUDE_LOCATION_INFO) != 0;
7653 switch (notificationType) {
7654 case ConnectivityManager.CALLBACK_AVAILABLE: {
7655 final NetworkCapabilities nc =
7656 networkCapabilitiesRestrictedForCallerPermissions(
7657 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
7658 putParcelable(
7659 bundle,
7660 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
7661 nc, includeLocationSensitiveInfo, nri.mPid, nri.mUid,
7662 nrForCallback.getRequestorPackageName(),
7663 nri.mCallingAttributionTag));
7664 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
7665 networkAgent.linkProperties, nri.mPid, nri.mUid));
7666 // For this notification, arg1 contains the blocked status.
7667 msg.arg1 = arg1;
7668 break;
7669 }
7670 case ConnectivityManager.CALLBACK_LOSING: {
7671 msg.arg1 = arg1;
7672 break;
7673 }
7674 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
7675 // networkAgent can't be null as it has been accessed a few lines above.
7676 final NetworkCapabilities netCap =
7677 networkCapabilitiesRestrictedForCallerPermissions(
7678 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
7679 putParcelable(
7680 bundle,
7681 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
7682 netCap, includeLocationSensitiveInfo, nri.mPid, nri.mUid,
7683 nrForCallback.getRequestorPackageName(),
7684 nri.mCallingAttributionTag));
7685 break;
7686 }
7687 case ConnectivityManager.CALLBACK_IP_CHANGED: {
7688 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
7689 networkAgent.linkProperties, nri.mPid, nri.mUid));
7690 break;
7691 }
7692 case ConnectivityManager.CALLBACK_BLK_CHANGED: {
7693 maybeLogBlockedStatusChanged(nri, networkAgent.network, arg1);
7694 msg.arg1 = arg1;
7695 break;
7696 }
7697 }
7698 msg.what = notificationType;
7699 msg.setData(bundle);
7700 try {
7701 if (VDBG) {
7702 String notification = ConnectivityManager.getCallbackName(notificationType);
7703 log("sending notification " + notification + " for " + nrForCallback);
7704 }
7705 nri.mMessenger.send(msg);
7706 } catch (RemoteException e) {
7707 // may occur naturally in the race of binder death.
7708 loge("RemoteException caught trying to send a callback msg for " + nrForCallback);
7709 }
7710 }
7711
7712 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
7713 bundle.putParcelable(t.getClass().getSimpleName(), t);
7714 }
7715
7716 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
7717 if (nai.numRequestNetworkRequests() != 0) {
7718 for (int i = 0; i < nai.numNetworkRequests(); i++) {
7719 NetworkRequest nr = nai.requestAt(i);
7720 // Ignore listening and track default requests.
7721 if (!nr.isRequest()) continue;
7722 loge("Dead network still had at least " + nr);
7723 break;
7724 }
7725 }
7726 nai.disconnect();
7727 }
7728
7729 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
7730 if (oldNetwork == null) {
7731 loge("Unknown NetworkAgentInfo in handleLingerComplete");
7732 return;
7733 }
7734 if (DBG) log("handleLingerComplete for " + oldNetwork.toShortString());
7735
7736 // If we get here it means that the last linger timeout for this network expired. So there
7737 // must be no other active linger timers, and we must stop lingering.
7738 oldNetwork.clearInactivityState();
7739
7740 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
7741 // Tear the network down.
7742 teardownUnneededNetwork(oldNetwork);
7743 } else {
7744 // Put the network in the background if it doesn't satisfy any foreground request.
7745 updateCapabilitiesForNetwork(oldNetwork);
7746 }
7747 }
7748
7749 private void processDefaultNetworkChanges(@NonNull final NetworkReassignment changes) {
7750 boolean isDefaultChanged = false;
7751 for (final NetworkRequestInfo defaultRequestInfo : mDefaultNetworkRequests) {
7752 final NetworkReassignment.RequestReassignment reassignment =
7753 changes.getReassignment(defaultRequestInfo);
7754 if (null == reassignment) {
7755 continue;
7756 }
7757 // reassignment only contains those instances where the satisfying network changed.
7758 isDefaultChanged = true;
7759 // Notify system services of the new default.
7760 makeDefault(defaultRequestInfo, reassignment.mOldNetwork, reassignment.mNewNetwork);
7761 }
7762
7763 if (isDefaultChanged) {
7764 // Hold a wakelock for a short time to help apps in migrating to a new default.
7765 scheduleReleaseNetworkTransitionWakelock();
7766 }
7767 }
7768
7769 private void makeDefault(@NonNull final NetworkRequestInfo nri,
7770 @Nullable final NetworkAgentInfo oldDefaultNetwork,
7771 @Nullable final NetworkAgentInfo newDefaultNetwork) {
7772 if (DBG) {
7773 log("Switching to new default network for: " + nri + " using " + newDefaultNetwork);
7774 }
7775
7776 // Fix up the NetworkCapabilities of any networks that have this network as underlying.
7777 if (newDefaultNetwork != null) {
7778 propagateUnderlyingNetworkCapabilities(newDefaultNetwork.network);
7779 }
7780
7781 // Set an app level managed default and return since further processing only applies to the
7782 // default network.
7783 if (mDefaultRequest != nri) {
7784 makeDefaultForApps(nri, oldDefaultNetwork, newDefaultNetwork);
7785 return;
7786 }
7787
7788 makeDefaultNetwork(newDefaultNetwork);
7789
7790 if (oldDefaultNetwork != null) {
7791 mLingerMonitor.noteLingerDefaultNetwork(oldDefaultNetwork, newDefaultNetwork);
7792 }
7793 mNetworkActivityTracker.updateDataActivityTracking(newDefaultNetwork, oldDefaultNetwork);
7794 handleApplyDefaultProxy(null != newDefaultNetwork
7795 ? newDefaultNetwork.linkProperties.getHttpProxy() : null);
7796 updateTcpBufferSizes(null != newDefaultNetwork
7797 ? newDefaultNetwork.linkProperties.getTcpBufferSizes() : null);
7798 notifyIfacesChangedForNetworkStats();
7799 }
7800
7801 private void makeDefaultForApps(@NonNull final NetworkRequestInfo nri,
7802 @Nullable final NetworkAgentInfo oldDefaultNetwork,
7803 @Nullable final NetworkAgentInfo newDefaultNetwork) {
7804 try {
7805 if (VDBG) {
7806 log("Setting default network for " + nri
7807 + " using UIDs " + nri.getUids()
7808 + " with old network " + (oldDefaultNetwork != null
7809 ? oldDefaultNetwork.network().getNetId() : "null")
7810 + " and new network " + (newDefaultNetwork != null
7811 ? newDefaultNetwork.network().getNetId() : "null"));
7812 }
7813 if (nri.getUids().isEmpty()) {
7814 throw new IllegalStateException("makeDefaultForApps called without specifying"
7815 + " any applications to set as the default." + nri);
7816 }
7817 if (null != newDefaultNetwork) {
paulhude2a2392021-06-09 16:11:35 +08007818 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00007819 newDefaultNetwork.network.getNetId(),
paulhude2a2392021-06-09 16:11:35 +08007820 toUidRangeStableParcels(nri.getUids()),
7821 nri.getDefaultNetworkPriority()));
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00007822 }
7823 if (null != oldDefaultNetwork) {
paulhude2a2392021-06-09 16:11:35 +08007824 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00007825 oldDefaultNetwork.network.getNetId(),
paulhude2a2392021-06-09 16:11:35 +08007826 toUidRangeStableParcels(nri.getUids()),
7827 nri.getDefaultNetworkPriority()));
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00007828 }
7829 } catch (RemoteException | ServiceSpecificException e) {
7830 loge("Exception setting app default network", e);
7831 }
7832 }
7833
7834 private void makeDefaultNetwork(@Nullable final NetworkAgentInfo newDefaultNetwork) {
7835 try {
7836 if (null != newDefaultNetwork) {
7837 mNetd.networkSetDefault(newDefaultNetwork.network.getNetId());
7838 } else {
7839 mNetd.networkClearDefault();
7840 }
7841 } catch (RemoteException | ServiceSpecificException e) {
7842 loge("Exception setting default network :" + e);
7843 }
7844 }
7845
7846 private void processListenRequests(@NonNull final NetworkAgentInfo nai) {
7847 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
7848 processNewlyLostListenRequests(nai);
7849 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
7850 processNewlySatisfiedListenRequests(nai);
7851 }
7852
7853 private void processNewlyLostListenRequests(@NonNull final NetworkAgentInfo nai) {
7854 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
7855 if (nri.isMultilayerRequest()) {
7856 continue;
7857 }
7858 final NetworkRequest nr = nri.mRequests.get(0);
7859 if (!nr.isListen()) continue;
7860 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
7861 nai.removeRequest(nr.requestId);
7862 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
7863 }
7864 }
7865 }
7866
7867 private void processNewlySatisfiedListenRequests(@NonNull final NetworkAgentInfo nai) {
7868 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
7869 if (nri.isMultilayerRequest()) {
7870 continue;
7871 }
7872 final NetworkRequest nr = nri.mRequests.get(0);
7873 if (!nr.isListen()) continue;
7874 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
7875 nai.addRequest(nr);
7876 notifyNetworkAvailable(nai, nri);
7877 }
7878 }
7879 }
7880
7881 // An accumulator class to gather the list of changes that result from a rematch.
7882 private static class NetworkReassignment {
7883 static class RequestReassignment {
7884 @NonNull public final NetworkRequestInfo mNetworkRequestInfo;
7885 @Nullable public final NetworkRequest mOldNetworkRequest;
7886 @Nullable public final NetworkRequest mNewNetworkRequest;
7887 @Nullable public final NetworkAgentInfo mOldNetwork;
7888 @Nullable public final NetworkAgentInfo mNewNetwork;
7889 RequestReassignment(@NonNull final NetworkRequestInfo networkRequestInfo,
7890 @Nullable final NetworkRequest oldNetworkRequest,
7891 @Nullable final NetworkRequest newNetworkRequest,
7892 @Nullable final NetworkAgentInfo oldNetwork,
7893 @Nullable final NetworkAgentInfo newNetwork) {
7894 mNetworkRequestInfo = networkRequestInfo;
7895 mOldNetworkRequest = oldNetworkRequest;
7896 mNewNetworkRequest = newNetworkRequest;
7897 mOldNetwork = oldNetwork;
7898 mNewNetwork = newNetwork;
7899 }
7900
7901 public String toString() {
7902 final NetworkRequest requestToShow = null != mNewNetworkRequest
7903 ? mNewNetworkRequest : mNetworkRequestInfo.mRequests.get(0);
7904 return requestToShow.requestId + " : "
7905 + (null != mOldNetwork ? mOldNetwork.network.getNetId() : "null")
7906 + " → " + (null != mNewNetwork ? mNewNetwork.network.getNetId() : "null");
7907 }
7908 }
7909
7910 @NonNull private final ArrayList<RequestReassignment> mReassignments = new ArrayList<>();
7911
7912 @NonNull Iterable<RequestReassignment> getRequestReassignments() {
7913 return mReassignments;
7914 }
7915
7916 void addRequestReassignment(@NonNull final RequestReassignment reassignment) {
7917 if (Build.isDebuggable()) {
7918 // The code is never supposed to add two reassignments of the same request. Make
7919 // sure this stays true, but without imposing this expensive check on all
7920 // reassignments on all user devices.
7921 for (final RequestReassignment existing : mReassignments) {
7922 if (existing.mNetworkRequestInfo.equals(reassignment.mNetworkRequestInfo)) {
7923 throw new IllegalStateException("Trying to reassign ["
7924 + reassignment + "] but already have ["
7925 + existing + "]");
7926 }
7927 }
7928 }
7929 mReassignments.add(reassignment);
7930 }
7931
7932 // Will return null if this reassignment does not change the network assigned to
7933 // the passed request.
7934 @Nullable
7935 private RequestReassignment getReassignment(@NonNull final NetworkRequestInfo nri) {
7936 for (final RequestReassignment event : getRequestReassignments()) {
7937 if (nri == event.mNetworkRequestInfo) return event;
7938 }
7939 return null;
7940 }
7941
7942 public String toString() {
7943 final StringJoiner sj = new StringJoiner(", " /* delimiter */,
7944 "NetReassign [" /* prefix */, "]" /* suffix */);
7945 if (mReassignments.isEmpty()) return sj.add("no changes").toString();
7946 for (final RequestReassignment rr : getRequestReassignments()) {
7947 sj.add(rr.toString());
7948 }
7949 return sj.toString();
7950 }
7951
7952 public String debugString() {
7953 final StringBuilder sb = new StringBuilder();
7954 sb.append("NetworkReassignment :");
7955 if (mReassignments.isEmpty()) return sb.append(" no changes").toString();
7956 for (final RequestReassignment rr : getRequestReassignments()) {
7957 sb.append("\n ").append(rr);
7958 }
7959 return sb.append("\n").toString();
7960 }
7961 }
7962
7963 private void updateSatisfiersForRematchRequest(@NonNull final NetworkRequestInfo nri,
7964 @Nullable final NetworkRequest previousRequest,
7965 @Nullable final NetworkRequest newRequest,
7966 @Nullable final NetworkAgentInfo previousSatisfier,
7967 @Nullable final NetworkAgentInfo newSatisfier,
7968 final long now) {
7969 if (null != newSatisfier && mNoServiceNetwork != newSatisfier) {
7970 if (VDBG) log("rematch for " + newSatisfier.toShortString());
7971 if (null != previousRequest && null != previousSatisfier) {
7972 if (VDBG || DDBG) {
7973 log(" accepting network in place of " + previousSatisfier.toShortString());
7974 }
7975 previousSatisfier.removeRequest(previousRequest.requestId);
7976 previousSatisfier.lingerRequest(previousRequest.requestId, now);
7977 } else {
7978 if (VDBG || DDBG) log(" accepting network in place of null");
7979 }
7980
7981 // To prevent constantly CPU wake up for nascent timer, if a network comes up
7982 // and immediately satisfies a request then remove the timer. This will happen for
7983 // all networks except in the case of an underlying network for a VCN.
7984 if (newSatisfier.isNascent()) {
7985 newSatisfier.unlingerRequest(NetworkRequest.REQUEST_ID_NONE);
7986 newSatisfier.unsetInactive();
7987 }
7988
7989 // if newSatisfier is not null, then newRequest may not be null.
7990 newSatisfier.unlingerRequest(newRequest.requestId);
7991 if (!newSatisfier.addRequest(newRequest)) {
7992 Log.wtf(TAG, "BUG: " + newSatisfier.toShortString() + " already has "
7993 + newRequest);
7994 }
7995 } else if (null != previousRequest && null != previousSatisfier) {
7996 if (DBG) {
7997 log("Network " + previousSatisfier.toShortString() + " stopped satisfying"
7998 + " request " + previousRequest.requestId);
7999 }
8000 previousSatisfier.removeRequest(previousRequest.requestId);
8001 }
8002 nri.setSatisfier(newSatisfier, newRequest);
8003 }
8004
8005 /**
8006 * This function is triggered when something can affect what network should satisfy what
8007 * request, and it computes the network reassignment from the passed collection of requests to
8008 * network match to the one that the system should now have. That data is encoded in an
8009 * object that is a list of changes, each of them having an NRI, and old satisfier, and a new
8010 * satisfier.
8011 *
8012 * After the reassignment is computed, it is applied to the state objects.
8013 *
8014 * @param networkRequests the nri objects to evaluate for possible network reassignment
8015 * @return NetworkReassignment listing of proposed network assignment changes
8016 */
8017 @NonNull
8018 private NetworkReassignment computeNetworkReassignment(
8019 @NonNull final Collection<NetworkRequestInfo> networkRequests) {
8020 final NetworkReassignment changes = new NetworkReassignment();
8021
8022 // Gather the list of all relevant agents.
8023 final ArrayList<NetworkAgentInfo> nais = new ArrayList<>();
8024 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
8025 if (!nai.everConnected) {
8026 continue;
8027 }
8028 nais.add(nai);
8029 }
8030
8031 for (final NetworkRequestInfo nri : networkRequests) {
8032 // Non-multilayer listen requests can be ignored.
8033 if (!nri.isMultilayerRequest() && nri.mRequests.get(0).isListen()) {
8034 continue;
8035 }
8036 NetworkAgentInfo bestNetwork = null;
8037 NetworkRequest bestRequest = null;
8038 for (final NetworkRequest req : nri.mRequests) {
8039 bestNetwork = mNetworkRanker.getBestNetwork(req, nais, nri.getSatisfier());
8040 // Stop evaluating as the highest possible priority request is satisfied.
8041 if (null != bestNetwork) {
8042 bestRequest = req;
8043 break;
8044 }
8045 }
8046 if (null == bestNetwork && isDefaultBlocked(nri)) {
8047 // Remove default networking if disallowed for managed default requests.
8048 bestNetwork = mNoServiceNetwork;
8049 }
8050 if (nri.getSatisfier() != bestNetwork) {
8051 // bestNetwork may be null if no network can satisfy this request.
8052 changes.addRequestReassignment(new NetworkReassignment.RequestReassignment(
8053 nri, nri.mActiveRequest, bestRequest, nri.getSatisfier(), bestNetwork));
8054 }
8055 }
8056 return changes;
8057 }
8058
8059 private Set<NetworkRequestInfo> getNrisFromGlobalRequests() {
8060 return new HashSet<>(mNetworkRequests.values());
8061 }
8062
8063 /**
8064 * Attempt to rematch all Networks with all NetworkRequests. This may result in Networks
8065 * being disconnected.
8066 */
8067 private void rematchAllNetworksAndRequests() {
8068 rematchNetworksAndRequests(getNrisFromGlobalRequests());
8069 }
8070
8071 /**
8072 * Attempt to rematch all Networks with given NetworkRequests. This may result in Networks
8073 * being disconnected.
8074 */
8075 private void rematchNetworksAndRequests(
8076 @NonNull final Set<NetworkRequestInfo> networkRequests) {
8077 ensureRunningOnConnectivityServiceThread();
8078 // TODO: This may be slow, and should be optimized.
8079 final long now = SystemClock.elapsedRealtime();
8080 final NetworkReassignment changes = computeNetworkReassignment(networkRequests);
8081 if (VDBG || DDBG) {
8082 log(changes.debugString());
8083 } else if (DBG) {
8084 log(changes.toString()); // Shorter form, only one line of log
8085 }
8086 applyNetworkReassignment(changes, now);
8087 issueNetworkNeeds();
8088 }
8089
8090 private void applyNetworkReassignment(@NonNull final NetworkReassignment changes,
8091 final long now) {
8092 final Collection<NetworkAgentInfo> nais = mNetworkAgentInfos;
8093
8094 // Since most of the time there are only 0 or 1 background networks, it would probably
8095 // be more efficient to just use an ArrayList here. TODO : measure performance
8096 final ArraySet<NetworkAgentInfo> oldBgNetworks = new ArraySet<>();
8097 for (final NetworkAgentInfo nai : nais) {
8098 if (nai.isBackgroundNetwork()) oldBgNetworks.add(nai);
8099 }
8100
8101 // First, update the lists of satisfied requests in the network agents. This is necessary
8102 // because some code later depends on this state to be correct, most prominently computing
8103 // the linger status.
8104 for (final NetworkReassignment.RequestReassignment event :
8105 changes.getRequestReassignments()) {
8106 updateSatisfiersForRematchRequest(event.mNetworkRequestInfo,
8107 event.mOldNetworkRequest, event.mNewNetworkRequest,
8108 event.mOldNetwork, event.mNewNetwork,
8109 now);
8110 }
8111
8112 // Process default network changes if applicable.
8113 processDefaultNetworkChanges(changes);
8114
8115 // Notify requested networks are available after the default net is switched, but
8116 // before LegacyTypeTracker sends legacy broadcasts
8117 for (final NetworkReassignment.RequestReassignment event :
8118 changes.getRequestReassignments()) {
8119 if (null != event.mNewNetwork) {
8120 notifyNetworkAvailable(event.mNewNetwork, event.mNetworkRequestInfo);
8121 } else {
8122 callCallbackForRequest(event.mNetworkRequestInfo, event.mOldNetwork,
8123 ConnectivityManager.CALLBACK_LOST, 0);
8124 }
8125 }
8126
8127 // Update the inactivity state before processing listen callbacks, because the background
8128 // computation depends on whether the network is inactive. Don't send the LOSING callbacks
8129 // just yet though, because they have to be sent after the listens are processed to keep
8130 // backward compatibility.
8131 final ArrayList<NetworkAgentInfo> inactiveNetworks = new ArrayList<>();
8132 for (final NetworkAgentInfo nai : nais) {
8133 // Rematching may have altered the inactivity state of some networks, so update all
8134 // inactivity timers. updateInactivityState reads the state from the network agent
8135 // and does nothing if the state has not changed : the source of truth is controlled
8136 // with NetworkAgentInfo#lingerRequest and NetworkAgentInfo#unlingerRequest, which
8137 // have been called while rematching the individual networks above.
8138 if (updateInactivityState(nai, now)) {
8139 inactiveNetworks.add(nai);
8140 }
8141 }
8142
8143 for (final NetworkAgentInfo nai : nais) {
8144 if (!nai.everConnected) continue;
8145 final boolean oldBackground = oldBgNetworks.contains(nai);
8146 // Process listen requests and update capabilities if the background state has
8147 // changed for this network. For consistency with previous behavior, send onLost
8148 // callbacks before onAvailable.
8149 processNewlyLostListenRequests(nai);
8150 if (oldBackground != nai.isBackgroundNetwork()) {
8151 applyBackgroundChangeForRematch(nai);
8152 }
8153 processNewlySatisfiedListenRequests(nai);
8154 }
8155
8156 for (final NetworkAgentInfo nai : inactiveNetworks) {
8157 // For nascent networks, if connecting with no foreground request, skip broadcasting
8158 // LOSING for backward compatibility. This is typical when mobile data connected while
8159 // wifi connected with mobile data always-on enabled.
8160 if (nai.isNascent()) continue;
8161 notifyNetworkLosing(nai, now);
8162 }
8163
8164 updateLegacyTypeTrackerAndVpnLockdownForRematch(changes, nais);
8165
8166 // Tear down all unneeded networks.
8167 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
8168 if (unneeded(nai, UnneededFor.TEARDOWN)) {
8169 if (nai.getInactivityExpiry() > 0) {
8170 // This network has active linger timers and no requests, but is not
8171 // lingering. Linger it.
8172 //
8173 // One way (the only way?) this can happen if this network is unvalidated
8174 // and became unneeded due to another network improving its score to the
8175 // point where this network will no longer be able to satisfy any requests
8176 // even if it validates.
8177 if (updateInactivityState(nai, now)) {
8178 notifyNetworkLosing(nai, now);
8179 }
8180 } else {
8181 if (DBG) log("Reaping " + nai.toShortString());
8182 teardownUnneededNetwork(nai);
8183 }
8184 }
8185 }
8186 }
8187
8188 /**
8189 * Apply a change in background state resulting from rematching networks with requests.
8190 *
8191 * During rematch, a network may change background states by starting to satisfy or stopping
8192 * to satisfy a foreground request. Listens don't count for this. When a network changes
8193 * background states, its capabilities need to be updated and callbacks fired for the
8194 * capability change.
8195 *
8196 * @param nai The network that changed background states
8197 */
8198 private void applyBackgroundChangeForRematch(@NonNull final NetworkAgentInfo nai) {
8199 final NetworkCapabilities newNc = mixInCapabilities(nai, nai.networkCapabilities);
8200 if (Objects.equals(nai.networkCapabilities, newNc)) return;
8201 updateNetworkPermissions(nai, newNc);
8202 nai.getAndSetNetworkCapabilities(newNc);
8203 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
8204 }
8205
8206 private void updateLegacyTypeTrackerAndVpnLockdownForRematch(
8207 @NonNull final NetworkReassignment changes,
8208 @NonNull final Collection<NetworkAgentInfo> nais) {
8209 final NetworkReassignment.RequestReassignment reassignmentOfDefault =
8210 changes.getReassignment(mDefaultRequest);
8211 final NetworkAgentInfo oldDefaultNetwork =
8212 null != reassignmentOfDefault ? reassignmentOfDefault.mOldNetwork : null;
8213 final NetworkAgentInfo newDefaultNetwork =
8214 null != reassignmentOfDefault ? reassignmentOfDefault.mNewNetwork : null;
8215
8216 if (oldDefaultNetwork != newDefaultNetwork) {
8217 // Maintain the illusion : since the legacy API only understands one network at a time,
8218 // if the default network changed, apps should see a disconnected broadcast for the
8219 // old default network before they see a connected broadcast for the new one.
8220 if (oldDefaultNetwork != null) {
8221 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
8222 oldDefaultNetwork, true);
8223 }
8224 if (newDefaultNetwork != null) {
8225 // The new default network can be newly null if and only if the old default
8226 // network doesn't satisfy the default request any more because it lost a
8227 // capability.
8228 mDefaultInetConditionPublished = newDefaultNetwork.lastValidated ? 100 : 0;
8229 mLegacyTypeTracker.add(
8230 newDefaultNetwork.networkInfo.getType(), newDefaultNetwork);
8231 }
8232 }
8233
8234 // Now that all the callbacks have been sent, send the legacy network broadcasts
8235 // as needed. This is necessary so that legacy requests correctly bind dns
8236 // requests to this network. The legacy users are listening for this broadcast
8237 // and will generally do a dns request so they can ensureRouteToHost and if
8238 // they do that before the callbacks happen they'll use the default network.
8239 //
8240 // TODO: Is there still a race here? The legacy broadcast will be sent after sending
8241 // callbacks, but if apps can receive the broadcast before the callback, they still might
8242 // have an inconsistent view of networking.
8243 //
8244 // This *does* introduce a race where if the user uses the new api
8245 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
8246 // they may get old info. Reverse this after the old startUsing api is removed.
8247 // This is on top of the multiple intent sequencing referenced in the todo above.
8248 for (NetworkAgentInfo nai : nais) {
8249 if (nai.everConnected) {
8250 addNetworkToLegacyTypeTracker(nai);
8251 }
8252 }
8253 }
8254
8255 private void issueNetworkNeeds() {
8256 ensureRunningOnConnectivityServiceThread();
8257 for (final NetworkOfferInfo noi : mNetworkOffers) {
8258 issueNetworkNeeds(noi);
8259 }
8260 }
8261
8262 private void issueNetworkNeeds(@NonNull final NetworkOfferInfo noi) {
8263 ensureRunningOnConnectivityServiceThread();
8264 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
8265 informOffer(nri, noi.offer, mNetworkRanker);
8266 }
8267 }
8268
8269 /**
8270 * Inform a NetworkOffer about any new situation of a request.
8271 *
8272 * This function handles updates to offers. A number of events may happen that require
8273 * updating the registrant for this offer about the situation :
8274 * • The offer itself was updated. This may lead the offer to no longer being able
8275 * to satisfy a request or beat a satisfier (and therefore be no longer needed),
8276 * or conversely being strengthened enough to beat the satisfier (and therefore
8277 * start being needed)
8278 * • The network satisfying a request changed (including cases where the request
8279 * starts or stops being satisfied). The new network may be a stronger or weaker
8280 * match than the old one, possibly affecting whether the offer is needed.
8281 * • The network satisfying a request updated their score. This may lead the offer
8282 * to no longer be able to beat it if the current satisfier got better, or
8283 * conversely start being a good choice if the current satisfier got weaker.
8284 *
8285 * @param nri The request
8286 * @param offer The offer. This may be an updated offer.
8287 */
8288 private static void informOffer(@NonNull NetworkRequestInfo nri,
8289 @NonNull final NetworkOffer offer, @NonNull final NetworkRanker networkRanker) {
8290 final NetworkRequest activeRequest = nri.isBeingSatisfied() ? nri.getActiveRequest() : null;
8291 final NetworkAgentInfo satisfier = null != activeRequest ? nri.getSatisfier() : null;
8292
8293 // Multi-layer requests have a currently active request, the one being satisfied.
8294 // Since the system will try to bring up a better network than is currently satisfying
8295 // the request, NetworkProviders need to be told the offers matching the requests *above*
8296 // the currently satisfied one are needed, that the ones *below* the satisfied one are
8297 // not needed, and the offer is needed for the active request iff the offer can beat
8298 // the satisfier.
8299 // For non-multilayer requests, the logic above gracefully degenerates to only the
8300 // last case.
8301 // To achieve this, the loop below will proceed in three steps. In a first phase, inform
8302 // providers that the offer is needed for this request, until the active request is found.
8303 // In a second phase, deal with the currently active request. In a third phase, inform
8304 // the providers that offer is unneeded for the remaining requests.
8305
8306 // First phase : inform providers of all requests above the active request.
8307 int i;
8308 for (i = 0; nri.mRequests.size() > i; ++i) {
8309 final NetworkRequest request = nri.mRequests.get(i);
8310 if (activeRequest == request) break; // Found the active request : go to phase 2
8311 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
8312 // Since this request is higher-priority than the one currently satisfied, if the
8313 // offer can satisfy it, the provider should try and bring up the network for sure ;
8314 // no need to even ask the ranker – an offer that can satisfy is always better than
8315 // no network. Hence tell the provider so unless it already knew.
8316 if (request.canBeSatisfiedBy(offer.caps) && !offer.neededFor(request)) {
8317 offer.onNetworkNeeded(request);
8318 }
8319 }
8320
8321 // Second phase : deal with the active request (if any)
8322 if (null != activeRequest && activeRequest.isRequest()) {
8323 final boolean oldNeeded = offer.neededFor(activeRequest);
8324 // An offer is needed if it is currently served by this provider or if this offer
8325 // can beat the current satisfier.
8326 final boolean currentlyServing = satisfier != null
8327 && satisfier.factorySerialNumber == offer.providerId;
8328 final boolean newNeeded = (currentlyServing
8329 || (activeRequest.canBeSatisfiedBy(offer.caps)
8330 && networkRanker.mightBeat(activeRequest, satisfier, offer)));
8331 if (newNeeded != oldNeeded) {
8332 if (newNeeded) {
8333 offer.onNetworkNeeded(activeRequest);
8334 } else {
8335 // The offer used to be able to beat the satisfier. Now it can't.
8336 offer.onNetworkUnneeded(activeRequest);
8337 }
8338 }
8339 }
8340
8341 // Third phase : inform the providers that the offer isn't needed for any request
8342 // below the active one.
8343 for (++i /* skip the active request */; nri.mRequests.size() > i; ++i) {
8344 final NetworkRequest request = nri.mRequests.get(i);
8345 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
8346 // Since this request is lower-priority than the one currently satisfied, if the
8347 // offer can satisfy it, the provider should not try and bring up the network.
8348 // Hence tell the provider so unless it already knew.
8349 if (offer.neededFor(request)) {
8350 offer.onNetworkUnneeded(request);
8351 }
8352 }
8353 }
8354
8355 private void addNetworkToLegacyTypeTracker(@NonNull final NetworkAgentInfo nai) {
8356 for (int i = 0; i < nai.numNetworkRequests(); i++) {
8357 NetworkRequest nr = nai.requestAt(i);
8358 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
8359 // legacy type tracker filters out repeat adds
8360 mLegacyTypeTracker.add(nr.legacyType, nai);
8361 }
8362 }
8363
8364 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
8365 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
8366 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
8367 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
8368 if (nai.isVPN()) {
8369 mLegacyTypeTracker.add(TYPE_VPN, nai);
8370 }
8371 }
8372
8373 private void updateInetCondition(NetworkAgentInfo nai) {
8374 // Don't bother updating until we've graduated to validated at least once.
8375 if (!nai.everValidated) return;
8376 // For now only update icons for the default connection.
8377 // TODO: Update WiFi and cellular icons separately. b/17237507
8378 if (!isDefaultNetwork(nai)) return;
8379
8380 int newInetCondition = nai.lastValidated ? 100 : 0;
8381 // Don't repeat publish.
8382 if (newInetCondition == mDefaultInetConditionPublished) return;
8383
8384 mDefaultInetConditionPublished = newInetCondition;
8385 sendInetConditionBroadcast(nai.networkInfo);
8386 }
8387
8388 @NonNull
8389 private NetworkInfo mixInInfo(@NonNull final NetworkAgentInfo nai, @NonNull NetworkInfo info) {
8390 final NetworkInfo newInfo = new NetworkInfo(info);
8391 // The suspended and roaming bits are managed in NetworkCapabilities.
8392 final boolean suspended =
8393 !nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
8394 if (suspended && info.getDetailedState() == NetworkInfo.DetailedState.CONNECTED) {
8395 // Only override the state with SUSPENDED if the network is currently in CONNECTED
8396 // state. This is because the network could have been suspended before connecting,
8397 // or it could be disconnecting while being suspended, and in both these cases
8398 // the state should not be overridden. Note that the only detailed state that
8399 // maps to State.CONNECTED is DetailedState.CONNECTED, so there is also no need to
8400 // worry about multiple different substates of CONNECTED.
8401 newInfo.setDetailedState(NetworkInfo.DetailedState.SUSPENDED, info.getReason(),
8402 info.getExtraInfo());
8403 } else if (!suspended && info.getDetailedState() == NetworkInfo.DetailedState.SUSPENDED) {
8404 // SUSPENDED state is currently only overridden from CONNECTED state. In the case the
8405 // network agent is created, then goes to suspended, then goes out of suspended without
8406 // ever setting connected. Check if network agent is ever connected to update the state.
8407 newInfo.setDetailedState(nai.everConnected
8408 ? NetworkInfo.DetailedState.CONNECTED
8409 : NetworkInfo.DetailedState.CONNECTING,
8410 info.getReason(),
8411 info.getExtraInfo());
8412 }
8413 newInfo.setRoaming(!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_ROAMING));
8414 return newInfo;
8415 }
8416
8417 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo info) {
8418 final NetworkInfo newInfo = mixInInfo(networkAgent, info);
8419
8420 final NetworkInfo.State state = newInfo.getState();
8421 NetworkInfo oldInfo = null;
8422 synchronized (networkAgent) {
8423 oldInfo = networkAgent.networkInfo;
8424 networkAgent.networkInfo = newInfo;
8425 }
8426
8427 if (DBG) {
8428 log(networkAgent.toShortString() + " EVENT_NETWORK_INFO_CHANGED, going from "
8429 + oldInfo.getState() + " to " + state);
8430 }
8431
8432 if (!networkAgent.created
8433 && (state == NetworkInfo.State.CONNECTED
8434 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
8435
8436 // A network that has just connected has zero requests and is thus a foreground network.
8437 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
8438
8439 if (!createNativeNetwork(networkAgent)) return;
Treehugger Robot4703a8c2021-07-02 13:55:33 +00008440 if (networkAgent.propagateUnderlyingCapabilities()) {
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00008441 // Initialize the network's capabilities to their starting values according to the
8442 // underlying networks. This ensures that the capabilities are correct before
8443 // anything happens to the network.
8444 updateCapabilitiesForNetwork(networkAgent);
8445 }
8446 networkAgent.created = true;
8447 networkAgent.onNetworkCreated();
8448 }
8449
8450 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
8451 networkAgent.everConnected = true;
8452
8453 // NetworkCapabilities need to be set before sending the private DNS config to
8454 // NetworkMonitor, otherwise NetworkMonitor cannot determine if validation is required.
8455 networkAgent.getAndSetNetworkCapabilities(networkAgent.networkCapabilities);
8456
8457 handlePerNetworkPrivateDnsConfig(networkAgent, mDnsManager.getPrivateDnsConfig());
8458 updateLinkProperties(networkAgent, new LinkProperties(networkAgent.linkProperties),
8459 null);
8460
8461 // Until parceled LinkProperties are sent directly to NetworkMonitor, the connect
8462 // command must be sent after updating LinkProperties to maximize chances of
8463 // NetworkMonitor seeing the correct LinkProperties when starting.
8464 // TODO: pass LinkProperties to the NetworkMonitor in the notifyNetworkConnected call.
8465 if (networkAgent.networkAgentConfig.acceptPartialConnectivity) {
8466 networkAgent.networkMonitor().setAcceptPartialConnectivity();
8467 }
8468 networkAgent.networkMonitor().notifyNetworkConnected(
8469 new LinkProperties(networkAgent.linkProperties,
8470 true /* parcelSensitiveFields */),
8471 networkAgent.networkCapabilities);
8472 scheduleUnvalidatedPrompt(networkAgent);
8473
8474 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
8475 // be communicated to a particular NetworkAgent depends only on the network's immutable,
8476 // capabilities, so it only needs to be done once on initial connect, not every time the
8477 // network's capabilities change. Note that we do this before rematching the network,
8478 // so we could decide to tear it down immediately afterwards. That's fine though - on
8479 // disconnection NetworkAgents should stop any signal strength monitoring they have been
8480 // doing.
8481 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
8482
8483 // Before first rematching networks, put an inactivity timer without any request, this
8484 // allows {@code updateInactivityState} to update the state accordingly and prevent
8485 // tearing down for any {@code unneeded} evaluation in this period.
8486 // Note that the timer will not be rescheduled since the expiry time is
8487 // fixed after connection regardless of the network satisfying other requests or not.
8488 // But it will be removed as soon as the network satisfies a request for the first time.
8489 networkAgent.lingerRequest(NetworkRequest.REQUEST_ID_NONE,
8490 SystemClock.elapsedRealtime(), mNascentDelayMs);
8491 networkAgent.setInactive();
8492
8493 // Consider network even though it is not yet validated.
8494 rematchAllNetworksAndRequests();
8495
8496 // This has to happen after matching the requests, because callbacks are just requests.
8497 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
8498 } else if (state == NetworkInfo.State.DISCONNECTED) {
8499 networkAgent.disconnect();
8500 if (networkAgent.isVPN()) {
8501 updateUids(networkAgent, networkAgent.networkCapabilities, null);
8502 }
8503 disconnectAndDestroyNetwork(networkAgent);
8504 if (networkAgent.isVPN()) {
8505 // As the active or bound network changes for apps, broadcast the default proxy, as
8506 // apps may need to update their proxy data. This is called after disconnecting from
8507 // VPN to make sure we do not broadcast the old proxy data.
8508 // TODO(b/122649188): send the broadcast only to VPN users.
8509 mProxyTracker.sendProxyBroadcast();
8510 }
8511 } else if (networkAgent.created && (oldInfo.getState() == NetworkInfo.State.SUSPENDED ||
8512 state == NetworkInfo.State.SUSPENDED)) {
8513 mLegacyTypeTracker.update(networkAgent);
8514 }
8515 }
8516
8517 private void updateNetworkScore(@NonNull final NetworkAgentInfo nai, final NetworkScore score) {
8518 if (VDBG || DDBG) log("updateNetworkScore for " + nai.toShortString() + " to " + score);
8519 nai.setScore(score);
8520 rematchAllNetworksAndRequests();
8521 }
8522
8523 // Notify only this one new request of the current state. Transfer all the
8524 // current state by calling NetworkCapabilities and LinkProperties callbacks
8525 // so that callers can be guaranteed to have as close to atomicity in state
8526 // transfer as can be supported by this current API.
8527 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
8528 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
8529 if (nri.mPendingIntent != null) {
8530 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
8531 // Attempt no subsequent state pushes where intents are involved.
8532 return;
8533 }
8534
8535 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
8536 final boolean metered = nai.networkCapabilities.isMetered();
8537 final boolean vpnBlocked = isUidBlockedByVpn(nri.mAsUid, mVpnBlockedUidRanges);
8538 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE,
8539 getBlockedState(blockedReasons, metered, vpnBlocked));
8540 }
8541
8542 // Notify the requests on this NAI that the network is now lingered.
8543 private void notifyNetworkLosing(@NonNull final NetworkAgentInfo nai, final long now) {
8544 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
8545 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
8546 }
8547
8548 private static int getBlockedState(int reasons, boolean metered, boolean vpnBlocked) {
8549 if (!metered) reasons &= ~BLOCKED_METERED_REASON_MASK;
8550 return vpnBlocked
8551 ? reasons | BLOCKED_REASON_LOCKDOWN_VPN
8552 : reasons & ~BLOCKED_REASON_LOCKDOWN_VPN;
8553 }
8554
8555 private void setUidBlockedReasons(int uid, @BlockedReason int blockedReasons) {
8556 if (blockedReasons == BLOCKED_REASON_NONE) {
8557 mUidBlockedReasons.delete(uid);
8558 } else {
8559 mUidBlockedReasons.put(uid, blockedReasons);
8560 }
8561 }
8562
8563 /**
8564 * Notify of the blocked state apps with a registered callback matching a given NAI.
8565 *
8566 * Unlike other callbacks, blocked status is different between each individual uid. So for
8567 * any given nai, all requests need to be considered according to the uid who filed it.
8568 *
8569 * @param nai The target NetworkAgentInfo.
8570 * @param oldMetered True if the previous network capabilities were metered.
8571 * @param newMetered True if the current network capabilities are metered.
8572 * @param oldBlockedUidRanges list of UID ranges previously blocked by lockdown VPN.
8573 * @param newBlockedUidRanges list of UID ranges blocked by lockdown VPN.
8574 */
8575 private void maybeNotifyNetworkBlocked(NetworkAgentInfo nai, boolean oldMetered,
8576 boolean newMetered, List<UidRange> oldBlockedUidRanges,
8577 List<UidRange> newBlockedUidRanges) {
8578
8579 for (int i = 0; i < nai.numNetworkRequests(); i++) {
8580 NetworkRequest nr = nai.requestAt(i);
8581 NetworkRequestInfo nri = mNetworkRequests.get(nr);
8582
8583 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
8584 final boolean oldVpnBlocked = isUidBlockedByVpn(nri.mAsUid, oldBlockedUidRanges);
8585 final boolean newVpnBlocked = (oldBlockedUidRanges != newBlockedUidRanges)
8586 ? isUidBlockedByVpn(nri.mAsUid, newBlockedUidRanges)
8587 : oldVpnBlocked;
8588
8589 final int oldBlockedState = getBlockedState(blockedReasons, oldMetered, oldVpnBlocked);
8590 final int newBlockedState = getBlockedState(blockedReasons, newMetered, newVpnBlocked);
8591 if (oldBlockedState != newBlockedState) {
8592 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
8593 newBlockedState);
8594 }
8595 }
8596 }
8597
8598 /**
8599 * Notify apps with a given UID of the new blocked state according to new uid state.
8600 * @param uid The uid for which the rules changed.
8601 * @param blockedReasons The reasons for why an uid is blocked.
8602 */
8603 private void maybeNotifyNetworkBlockedForNewState(int uid, @BlockedReason int blockedReasons) {
8604 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
8605 final boolean metered = nai.networkCapabilities.isMetered();
8606 final boolean vpnBlocked = isUidBlockedByVpn(uid, mVpnBlockedUidRanges);
8607
8608 final int oldBlockedState = getBlockedState(
8609 mUidBlockedReasons.get(uid, BLOCKED_REASON_NONE), metered, vpnBlocked);
8610 final int newBlockedState = getBlockedState(blockedReasons, metered, vpnBlocked);
8611 if (oldBlockedState == newBlockedState) {
8612 continue;
8613 }
8614 for (int i = 0; i < nai.numNetworkRequests(); i++) {
8615 NetworkRequest nr = nai.requestAt(i);
8616 NetworkRequestInfo nri = mNetworkRequests.get(nr);
8617 if (nri != null && nri.mAsUid == uid) {
8618 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
8619 newBlockedState);
8620 }
8621 }
8622 }
8623 }
8624
8625 @VisibleForTesting
8626 protected void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
8627 // The NetworkInfo we actually send out has no bearing on the real
8628 // state of affairs. For example, if the default connection is mobile,
8629 // and a request for HIPRI has just gone away, we need to pretend that
8630 // HIPRI has just disconnected. So we need to set the type to HIPRI and
8631 // the state to DISCONNECTED, even though the network is of type MOBILE
8632 // and is still connected.
8633 NetworkInfo info = new NetworkInfo(nai.networkInfo);
8634 info.setType(type);
8635 filterForLegacyLockdown(info);
8636 if (state != DetailedState.DISCONNECTED) {
8637 info.setDetailedState(state, null, info.getExtraInfo());
8638 sendConnectedBroadcast(info);
8639 } else {
8640 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
8641 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
8642 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
8643 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
8644 if (info.isFailover()) {
8645 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
8646 nai.networkInfo.setFailover(false);
8647 }
8648 if (info.getReason() != null) {
8649 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
8650 }
8651 if (info.getExtraInfo() != null) {
8652 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
8653 }
8654 NetworkAgentInfo newDefaultAgent = null;
8655 if (nai.isSatisfyingRequest(mDefaultRequest.mRequests.get(0).requestId)) {
8656 newDefaultAgent = mDefaultRequest.getSatisfier();
8657 if (newDefaultAgent != null) {
8658 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
8659 newDefaultAgent.networkInfo);
8660 } else {
8661 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
8662 }
8663 }
8664 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
8665 mDefaultInetConditionPublished);
8666 sendStickyBroadcast(intent);
8667 if (newDefaultAgent != null) {
8668 sendConnectedBroadcast(newDefaultAgent.networkInfo);
8669 }
8670 }
8671 }
8672
8673 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
8674 if (VDBG || DDBG) {
8675 String notification = ConnectivityManager.getCallbackName(notifyType);
8676 log("notifyType " + notification + " for " + networkAgent.toShortString());
8677 }
8678 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
8679 NetworkRequest nr = networkAgent.requestAt(i);
8680 NetworkRequestInfo nri = mNetworkRequests.get(nr);
8681 if (VDBG) log(" sending notification for " + nr);
8682 if (nri.mPendingIntent == null) {
8683 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
8684 } else {
8685 sendPendingIntentForRequest(nri, networkAgent, notifyType);
8686 }
8687 }
8688 }
8689
8690 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
8691 notifyNetworkCallbacks(networkAgent, notifyType, 0);
8692 }
8693
8694 /**
8695 * Returns the list of all interfaces that could be used by network traffic that does not
8696 * explicitly specify a network. This includes the default network, but also all VPNs that are
8697 * currently connected.
8698 *
8699 * Must be called on the handler thread.
8700 */
8701 @NonNull
8702 private ArrayList<Network> getDefaultNetworks() {
8703 ensureRunningOnConnectivityServiceThread();
8704 final ArrayList<Network> defaultNetworks = new ArrayList<>();
8705 final Set<Integer> activeNetIds = new ArraySet<>();
8706 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
8707 if (nri.isBeingSatisfied()) {
8708 activeNetIds.add(nri.getSatisfier().network().netId);
8709 }
8710 }
8711 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
8712 if (nai.everConnected && (activeNetIds.contains(nai.network().netId) || nai.isVPN())) {
8713 defaultNetworks.add(nai.network);
8714 }
8715 }
8716 return defaultNetworks;
8717 }
8718
8719 /**
8720 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
8721 * active iface's tracked properties has changed.
8722 */
8723 private void notifyIfacesChangedForNetworkStats() {
8724 ensureRunningOnConnectivityServiceThread();
8725 String activeIface = null;
8726 LinkProperties activeLinkProperties = getActiveLinkProperties();
8727 if (activeLinkProperties != null) {
8728 activeIface = activeLinkProperties.getInterfaceName();
8729 }
8730
8731 final UnderlyingNetworkInfo[] underlyingNetworkInfos = getAllVpnInfo();
8732 try {
8733 final ArrayList<NetworkStateSnapshot> snapshots = new ArrayList<>();
junyulai0f570222021-03-05 14:46:25 +08008734 for (final NetworkStateSnapshot snapshot : getAllNetworkStateSnapshots()) {
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00008735 snapshots.add(snapshot);
8736 }
8737 mStatsManager.notifyNetworkStatus(getDefaultNetworks(),
8738 snapshots, activeIface, Arrays.asList(underlyingNetworkInfos));
8739 } catch (Exception ignored) {
8740 }
8741 }
8742
8743 @Override
8744 public String getCaptivePortalServerUrl() {
8745 enforceNetworkStackOrSettingsPermission();
8746 String settingUrl = mResources.get().getString(
8747 R.string.config_networkCaptivePortalServerUrl);
8748
8749 if (!TextUtils.isEmpty(settingUrl)) {
8750 return settingUrl;
8751 }
8752
8753 settingUrl = Settings.Global.getString(mContext.getContentResolver(),
8754 ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL);
8755 if (!TextUtils.isEmpty(settingUrl)) {
8756 return settingUrl;
8757 }
8758
8759 return DEFAULT_CAPTIVE_PORTAL_HTTP_URL;
8760 }
8761
8762 @Override
8763 public void startNattKeepalive(Network network, int intervalSeconds,
8764 ISocketKeepaliveCallback cb, String srcAddr, int srcPort, String dstAddr) {
8765 enforceKeepalivePermission();
8766 mKeepaliveTracker.startNattKeepalive(
8767 getNetworkAgentInfoForNetwork(network), null /* fd */,
8768 intervalSeconds, cb,
8769 srcAddr, srcPort, dstAddr, NattSocketKeepalive.NATT_PORT);
8770 }
8771
8772 @Override
8773 public void startNattKeepaliveWithFd(Network network, ParcelFileDescriptor pfd, int resourceId,
8774 int intervalSeconds, ISocketKeepaliveCallback cb, String srcAddr,
8775 String dstAddr) {
8776 try {
8777 final FileDescriptor fd = pfd.getFileDescriptor();
8778 mKeepaliveTracker.startNattKeepalive(
8779 getNetworkAgentInfoForNetwork(network), fd, resourceId,
8780 intervalSeconds, cb,
8781 srcAddr, dstAddr, NattSocketKeepalive.NATT_PORT);
8782 } finally {
8783 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
8784 // startNattKeepalive calls Os.dup(fd) before returning, so we can close immediately.
8785 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
8786 IoUtils.closeQuietly(pfd);
8787 }
8788 }
8789 }
8790
8791 @Override
8792 public void startTcpKeepalive(Network network, ParcelFileDescriptor pfd, int intervalSeconds,
8793 ISocketKeepaliveCallback cb) {
8794 try {
8795 enforceKeepalivePermission();
8796 final FileDescriptor fd = pfd.getFileDescriptor();
8797 mKeepaliveTracker.startTcpKeepalive(
8798 getNetworkAgentInfoForNetwork(network), fd, intervalSeconds, cb);
8799 } finally {
8800 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
8801 // startTcpKeepalive calls Os.dup(fd) before returning, so we can close immediately.
8802 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
8803 IoUtils.closeQuietly(pfd);
8804 }
8805 }
8806 }
8807
8808 @Override
8809 public void stopKeepalive(Network network, int slot) {
8810 mHandler.sendMessage(mHandler.obtainMessage(
8811 NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE, slot, SocketKeepalive.SUCCESS, network));
8812 }
8813
8814 @Override
8815 public void factoryReset() {
8816 enforceSettingsPermission();
8817
Treehugger Robotfac2a722021-05-21 02:42:59 +00008818 final int uid = mDeps.getCallingUid();
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00008819 final long token = Binder.clearCallingIdentity();
8820 try {
Treehugger Robotfac2a722021-05-21 02:42:59 +00008821 if (mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_NETWORK_RESET,
8822 UserHandle.getUserHandleForUid(uid))) {
8823 return;
8824 }
8825
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00008826 final IpMemoryStore ipMemoryStore = IpMemoryStore.getMemoryStore(mContext);
8827 ipMemoryStore.factoryReset();
Treehugger Robotfac2a722021-05-21 02:42:59 +00008828
8829 // Turn airplane mode off
8830 setAirplaneMode(false);
8831
8832 // restore private DNS settings to default mode (opportunistic)
8833 if (!mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_CONFIG_PRIVATE_DNS,
8834 UserHandle.getUserHandleForUid(uid))) {
8835 ConnectivitySettingsManager.setPrivateDnsMode(mContext,
8836 PRIVATE_DNS_MODE_OPPORTUNISTIC);
8837 }
8838
8839 Settings.Global.putString(mContext.getContentResolver(),
8840 ConnectivitySettingsManager.NETWORK_AVOID_BAD_WIFI, null);
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00008841 } finally {
8842 Binder.restoreCallingIdentity(token);
8843 }
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00008844 }
8845
8846 @Override
8847 public byte[] getNetworkWatchlistConfigHash() {
8848 NetworkWatchlistManager nwm = mContext.getSystemService(NetworkWatchlistManager.class);
8849 if (nwm == null) {
8850 loge("Unable to get NetworkWatchlistManager");
8851 return null;
8852 }
8853 // Redirect it to network watchlist service to access watchlist file and calculate hash.
8854 return nwm.getWatchlistConfigHash();
8855 }
8856
8857 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
8858 int[] transports = nai.networkCapabilities.getTransportTypes();
8859 mMetricsLog.log(nai.network.getNetId(), transports, new NetworkEvent(evtype));
8860 }
8861
8862 private static boolean toBool(int encodedBoolean) {
8863 return encodedBoolean != 0; // Only 0 means false.
8864 }
8865
8866 private static int encodeBool(boolean b) {
8867 return b ? 1 : 0;
8868 }
8869
8870 @Override
8871 public int handleShellCommand(@NonNull ParcelFileDescriptor in,
8872 @NonNull ParcelFileDescriptor out, @NonNull ParcelFileDescriptor err,
8873 @NonNull String[] args) {
8874 return new ShellCmd().exec(this, in.getFileDescriptor(), out.getFileDescriptor(),
8875 err.getFileDescriptor(), args);
8876 }
8877
8878 private class ShellCmd extends BasicShellCommandHandler {
8879 @Override
8880 public int onCommand(String cmd) {
8881 if (cmd == null) {
8882 return handleDefaultCommands(cmd);
8883 }
8884 final PrintWriter pw = getOutPrintWriter();
8885 try {
8886 switch (cmd) {
8887 case "airplane-mode":
8888 final String action = getNextArg();
8889 if ("enable".equals(action)) {
8890 setAirplaneMode(true);
8891 return 0;
8892 } else if ("disable".equals(action)) {
8893 setAirplaneMode(false);
8894 return 0;
8895 } else if (action == null) {
8896 final ContentResolver cr = mContext.getContentResolver();
8897 final int enabled = Settings.Global.getInt(cr,
8898 Settings.Global.AIRPLANE_MODE_ON);
8899 pw.println(enabled == 0 ? "disabled" : "enabled");
8900 return 0;
8901 } else {
8902 onHelp();
8903 return -1;
8904 }
8905 default:
8906 return handleDefaultCommands(cmd);
8907 }
8908 } catch (Exception e) {
8909 pw.println(e);
8910 }
8911 return -1;
8912 }
8913
8914 @Override
8915 public void onHelp() {
8916 PrintWriter pw = getOutPrintWriter();
8917 pw.println("Connectivity service commands:");
8918 pw.println(" help");
8919 pw.println(" Print this help text.");
8920 pw.println(" airplane-mode [enable|disable]");
8921 pw.println(" Turn airplane mode on or off.");
8922 pw.println(" airplane-mode");
8923 pw.println(" Get airplane mode.");
8924 }
8925 }
8926
8927 private int getVpnType(@Nullable NetworkAgentInfo vpn) {
8928 if (vpn == null) return VpnManager.TYPE_VPN_NONE;
8929 final TransportInfo ti = vpn.networkCapabilities.getTransportInfo();
8930 if (!(ti instanceof VpnTransportInfo)) return VpnManager.TYPE_VPN_NONE;
8931 return ((VpnTransportInfo) ti).getType();
8932 }
8933
8934 /**
8935 * @param connectionInfo the connection to resolve.
8936 * @return {@code uid} if the connection is found and the app has permission to observe it
8937 * (e.g., if it is associated with the calling VPN app's tunnel) or {@code INVALID_UID} if the
8938 * connection is not found.
8939 */
8940 public int getConnectionOwnerUid(ConnectionInfo connectionInfo) {
8941 if (connectionInfo.protocol != IPPROTO_TCP && connectionInfo.protocol != IPPROTO_UDP) {
8942 throw new IllegalArgumentException("Unsupported protocol " + connectionInfo.protocol);
8943 }
8944
8945 final int uid = mDeps.getConnectionOwnerUid(connectionInfo.protocol,
8946 connectionInfo.local, connectionInfo.remote);
8947
8948 if (uid == INVALID_UID) return uid; // Not found.
8949
8950 // Connection owner UIDs are visible only to the network stack and to the VpnService-based
8951 // VPN, if any, that applies to the UID that owns the connection.
8952 if (checkNetworkStackPermission()) return uid;
8953
8954 final NetworkAgentInfo vpn = getVpnForUid(uid);
8955 if (vpn == null || getVpnType(vpn) != VpnManager.TYPE_VPN_SERVICE
8956 || vpn.networkCapabilities.getOwnerUid() != mDeps.getCallingUid()) {
8957 return INVALID_UID;
8958 }
8959
8960 return uid;
8961 }
8962
8963 /**
8964 * Returns a IBinder to a TestNetworkService. Will be lazily created as needed.
8965 *
8966 * <p>The TestNetworkService must be run in the system server due to TUN creation.
8967 */
8968 @Override
8969 public IBinder startOrGetTestNetworkService() {
8970 synchronized (mTNSLock) {
8971 TestNetworkService.enforceTestNetworkPermissions(mContext);
8972
8973 if (mTNS == null) {
8974 mTNS = new TestNetworkService(mContext);
8975 }
8976
8977 return mTNS;
8978 }
8979 }
8980
8981 /**
8982 * Handler used for managing all Connectivity Diagnostics related functions.
8983 *
8984 * @see android.net.ConnectivityDiagnosticsManager
8985 *
8986 * TODO(b/147816404): Explore moving ConnectivityDiagnosticsHandler to a separate file
8987 */
8988 @VisibleForTesting
8989 class ConnectivityDiagnosticsHandler extends Handler {
8990 private final String mTag = ConnectivityDiagnosticsHandler.class.getSimpleName();
8991
8992 /**
8993 * Used to handle ConnectivityDiagnosticsCallback registration events from {@link
8994 * android.net.ConnectivityDiagnosticsManager}.
8995 * obj = ConnectivityDiagnosticsCallbackInfo with IConnectivityDiagnosticsCallback and
8996 * NetworkRequestInfo to be registered
8997 */
8998 private static final int EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 1;
8999
9000 /**
9001 * Used to handle ConnectivityDiagnosticsCallback unregister events from {@link
9002 * android.net.ConnectivityDiagnosticsManager}.
9003 * obj = the IConnectivityDiagnosticsCallback to be unregistered
9004 * arg1 = the uid of the caller
9005 */
9006 private static final int EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 2;
9007
9008 /**
9009 * Event for {@link NetworkStateTrackerHandler} to trigger ConnectivityReport callbacks
9010 * after processing {@link #EVENT_NETWORK_TESTED} events.
9011 * obj = {@link ConnectivityReportEvent} representing ConnectivityReport info reported from
9012 * NetworkMonitor.
9013 * data = PersistableBundle of extras passed from NetworkMonitor.
9014 *
9015 * <p>See {@link ConnectivityService#EVENT_NETWORK_TESTED}.
9016 */
9017 private static final int EVENT_NETWORK_TESTED = ConnectivityService.EVENT_NETWORK_TESTED;
9018
9019 /**
9020 * Event for NetworkMonitor to inform ConnectivityService that a potential data stall has
9021 * been detected on the network.
9022 * obj = Long the timestamp (in millis) for when the suspected data stall was detected.
9023 * arg1 = {@link DataStallReport#DetectionMethod} indicating the detection method.
9024 * arg2 = NetID.
9025 * data = PersistableBundle of extras passed from NetworkMonitor.
9026 */
9027 private static final int EVENT_DATA_STALL_SUSPECTED = 4;
9028
9029 /**
9030 * Event for ConnectivityDiagnosticsHandler to handle network connectivity being reported to
9031 * the platform. This event will invoke {@link
9032 * IConnectivityDiagnosticsCallback#onNetworkConnectivityReported} for permissioned
9033 * callbacks.
9034 * obj = Network that was reported on
9035 * arg1 = boolint for the quality reported
9036 */
9037 private static final int EVENT_NETWORK_CONNECTIVITY_REPORTED = 5;
9038
9039 private ConnectivityDiagnosticsHandler(Looper looper) {
9040 super(looper);
9041 }
9042
9043 @Override
9044 public void handleMessage(Message msg) {
9045 switch (msg.what) {
9046 case EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
9047 handleRegisterConnectivityDiagnosticsCallback(
9048 (ConnectivityDiagnosticsCallbackInfo) msg.obj);
9049 break;
9050 }
9051 case EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
9052 handleUnregisterConnectivityDiagnosticsCallback(
9053 (IConnectivityDiagnosticsCallback) msg.obj, msg.arg1);
9054 break;
9055 }
9056 case EVENT_NETWORK_TESTED: {
9057 final ConnectivityReportEvent reportEvent =
9058 (ConnectivityReportEvent) msg.obj;
9059
9060 handleNetworkTestedWithExtras(reportEvent, reportEvent.mExtras);
9061 break;
9062 }
9063 case EVENT_DATA_STALL_SUSPECTED: {
9064 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
9065 final Pair<Long, PersistableBundle> arg =
9066 (Pair<Long, PersistableBundle>) msg.obj;
9067 if (nai == null) break;
9068
9069 handleDataStallSuspected(nai, arg.first, msg.arg1, arg.second);
9070 break;
9071 }
9072 case EVENT_NETWORK_CONNECTIVITY_REPORTED: {
9073 handleNetworkConnectivityReported((NetworkAgentInfo) msg.obj, toBool(msg.arg1));
9074 break;
9075 }
9076 default: {
9077 Log.e(mTag, "Unrecognized event in ConnectivityDiagnostics: " + msg.what);
9078 }
9079 }
9080 }
9081 }
9082
9083 /** Class used for cleaning up IConnectivityDiagnosticsCallback instances after their death. */
9084 @VisibleForTesting
9085 class ConnectivityDiagnosticsCallbackInfo implements Binder.DeathRecipient {
9086 @NonNull private final IConnectivityDiagnosticsCallback mCb;
9087 @NonNull private final NetworkRequestInfo mRequestInfo;
9088 @NonNull private final String mCallingPackageName;
9089
9090 @VisibleForTesting
9091 ConnectivityDiagnosticsCallbackInfo(
9092 @NonNull IConnectivityDiagnosticsCallback cb,
9093 @NonNull NetworkRequestInfo nri,
9094 @NonNull String callingPackageName) {
9095 mCb = cb;
9096 mRequestInfo = nri;
9097 mCallingPackageName = callingPackageName;
9098 }
9099
9100 @Override
9101 public void binderDied() {
9102 log("ConnectivityDiagnosticsCallback IBinder died.");
9103 unregisterConnectivityDiagnosticsCallback(mCb);
9104 }
9105 }
9106
9107 /**
9108 * Class used for sending information from {@link
9109 * NetworkMonitorCallbacks#notifyNetworkTestedWithExtras} to the handler for processing it.
9110 */
9111 private static class NetworkTestedResults {
9112 private final int mNetId;
9113 private final int mTestResult;
9114 private final long mTimestampMillis;
9115 @Nullable private final String mRedirectUrl;
9116
9117 private NetworkTestedResults(
9118 int netId, int testResult, long timestampMillis, @Nullable String redirectUrl) {
9119 mNetId = netId;
9120 mTestResult = testResult;
9121 mTimestampMillis = timestampMillis;
9122 mRedirectUrl = redirectUrl;
9123 }
9124 }
9125
9126 /**
9127 * Class used for sending information from {@link NetworkStateTrackerHandler} to {@link
9128 * ConnectivityDiagnosticsHandler}.
9129 */
9130 private static class ConnectivityReportEvent {
9131 private final long mTimestampMillis;
9132 @NonNull private final NetworkAgentInfo mNai;
9133 private final PersistableBundle mExtras;
9134
9135 private ConnectivityReportEvent(long timestampMillis, @NonNull NetworkAgentInfo nai,
9136 PersistableBundle p) {
9137 mTimestampMillis = timestampMillis;
9138 mNai = nai;
9139 mExtras = p;
9140 }
9141 }
9142
9143 private void handleRegisterConnectivityDiagnosticsCallback(
9144 @NonNull ConnectivityDiagnosticsCallbackInfo cbInfo) {
9145 ensureRunningOnConnectivityServiceThread();
9146
9147 final IConnectivityDiagnosticsCallback cb = cbInfo.mCb;
9148 final IBinder iCb = cb.asBinder();
9149 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
9150
9151 // Connectivity Diagnostics are meant to be used with a single network request. It would be
9152 // confusing for these networks to change when an NRI is satisfied in another layer.
9153 if (nri.isMultilayerRequest()) {
9154 throw new IllegalArgumentException("Connectivity Diagnostics do not support multilayer "
9155 + "network requests.");
9156 }
9157
9158 // This means that the client registered the same callback multiple times. Do
9159 // not override the previous entry, and exit silently.
9160 if (mConnectivityDiagnosticsCallbacks.containsKey(iCb)) {
9161 if (VDBG) log("Diagnostics callback is already registered");
9162
9163 // Decrement the reference count for this NetworkRequestInfo. The reference count is
9164 // incremented when the NetworkRequestInfo is created as part of
9165 // enforceRequestCountLimit().
9166 nri.decrementRequestCount();
9167 return;
9168 }
9169
9170 mConnectivityDiagnosticsCallbacks.put(iCb, cbInfo);
9171
9172 try {
9173 iCb.linkToDeath(cbInfo, 0);
9174 } catch (RemoteException e) {
9175 cbInfo.binderDied();
9176 return;
9177 }
9178
9179 // Once registered, provide ConnectivityReports for matching Networks
9180 final List<NetworkAgentInfo> matchingNetworks = new ArrayList<>();
9181 synchronized (mNetworkForNetId) {
9182 for (int i = 0; i < mNetworkForNetId.size(); i++) {
9183 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
9184 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0)
9185 if (nai.satisfies(nri.mRequests.get(0))) {
9186 matchingNetworks.add(nai);
9187 }
9188 }
9189 }
9190 for (final NetworkAgentInfo nai : matchingNetworks) {
9191 final ConnectivityReport report = nai.getConnectivityReport();
9192 if (report == null) {
9193 continue;
9194 }
9195 if (!checkConnectivityDiagnosticsPermissions(
9196 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
9197 continue;
9198 }
9199
9200 try {
9201 cb.onConnectivityReportAvailable(report);
9202 } catch (RemoteException e) {
9203 // Exception while sending the ConnectivityReport. Move on to the next network.
9204 }
9205 }
9206 }
9207
9208 private void handleUnregisterConnectivityDiagnosticsCallback(
9209 @NonNull IConnectivityDiagnosticsCallback cb, int uid) {
9210 ensureRunningOnConnectivityServiceThread();
9211 final IBinder iCb = cb.asBinder();
9212
9213 final ConnectivityDiagnosticsCallbackInfo cbInfo =
9214 mConnectivityDiagnosticsCallbacks.remove(iCb);
9215 if (cbInfo == null) {
9216 if (VDBG) log("Removing diagnostics callback that is not currently registered");
9217 return;
9218 }
9219
9220 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
9221
9222 // Caller's UID must either be the registrants (if they are unregistering) or the System's
9223 // (if the Binder died)
9224 if (uid != nri.mUid && uid != Process.SYSTEM_UID) {
9225 if (DBG) loge("Uid(" + uid + ") not registrant's (" + nri.mUid + ") or System's");
9226 return;
9227 }
9228
9229 // Decrement the reference count for this NetworkRequestInfo. The reference count is
9230 // incremented when the NetworkRequestInfo is created as part of
9231 // enforceRequestCountLimit().
9232 nri.decrementRequestCount();
9233
9234 iCb.unlinkToDeath(cbInfo, 0);
9235 }
9236
9237 private void handleNetworkTestedWithExtras(
9238 @NonNull ConnectivityReportEvent reportEvent, @NonNull PersistableBundle extras) {
9239 final NetworkAgentInfo nai = reportEvent.mNai;
9240 final NetworkCapabilities networkCapabilities =
9241 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
9242 final ConnectivityReport report =
9243 new ConnectivityReport(
9244 reportEvent.mNai.network,
9245 reportEvent.mTimestampMillis,
9246 nai.linkProperties,
9247 networkCapabilities,
9248 extras);
9249 nai.setConnectivityReport(report);
9250 final List<IConnectivityDiagnosticsCallback> results =
9251 getMatchingPermissionedCallbacks(nai);
9252 for (final IConnectivityDiagnosticsCallback cb : results) {
9253 try {
9254 cb.onConnectivityReportAvailable(report);
9255 } catch (RemoteException ex) {
9256 loge("Error invoking onConnectivityReport", ex);
9257 }
9258 }
9259 }
9260
9261 private void handleDataStallSuspected(
9262 @NonNull NetworkAgentInfo nai, long timestampMillis, int detectionMethod,
9263 @NonNull PersistableBundle extras) {
9264 final NetworkCapabilities networkCapabilities =
9265 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
9266 final DataStallReport report =
9267 new DataStallReport(
9268 nai.network,
9269 timestampMillis,
9270 detectionMethod,
9271 nai.linkProperties,
9272 networkCapabilities,
9273 extras);
9274 final List<IConnectivityDiagnosticsCallback> results =
9275 getMatchingPermissionedCallbacks(nai);
9276 for (final IConnectivityDiagnosticsCallback cb : results) {
9277 try {
9278 cb.onDataStallSuspected(report);
9279 } catch (RemoteException ex) {
9280 loge("Error invoking onDataStallSuspected", ex);
9281 }
9282 }
9283 }
9284
9285 private void handleNetworkConnectivityReported(
9286 @NonNull NetworkAgentInfo nai, boolean connectivity) {
9287 final List<IConnectivityDiagnosticsCallback> results =
9288 getMatchingPermissionedCallbacks(nai);
9289 for (final IConnectivityDiagnosticsCallback cb : results) {
9290 try {
9291 cb.onNetworkConnectivityReported(nai.network, connectivity);
9292 } catch (RemoteException ex) {
9293 loge("Error invoking onNetworkConnectivityReported", ex);
9294 }
9295 }
9296 }
9297
9298 private NetworkCapabilities getNetworkCapabilitiesWithoutUids(@NonNull NetworkCapabilities nc) {
9299 final NetworkCapabilities sanitized = new NetworkCapabilities(nc,
9300 NetworkCapabilities.REDACT_ALL);
9301 sanitized.setUids(null);
9302 sanitized.setAdministratorUids(new int[0]);
9303 sanitized.setOwnerUid(Process.INVALID_UID);
9304 return sanitized;
9305 }
9306
9307 private List<IConnectivityDiagnosticsCallback> getMatchingPermissionedCallbacks(
9308 @NonNull NetworkAgentInfo nai) {
9309 final List<IConnectivityDiagnosticsCallback> results = new ArrayList<>();
9310 for (Entry<IBinder, ConnectivityDiagnosticsCallbackInfo> entry :
9311 mConnectivityDiagnosticsCallbacks.entrySet()) {
9312 final ConnectivityDiagnosticsCallbackInfo cbInfo = entry.getValue();
9313 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
9314 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0).
9315 if (nai.satisfies(nri.mRequests.get(0))) {
9316 if (checkConnectivityDiagnosticsPermissions(
9317 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
9318 results.add(entry.getValue().mCb);
9319 }
9320 }
9321 }
9322 return results;
9323 }
9324
Treehugger Robot27b68882021-06-07 19:42:39 +00009325 private boolean isLocationPermissionRequiredForConnectivityDiagnostics(
9326 @NonNull NetworkAgentInfo nai) {
9327 // TODO(b/188483916): replace with a transport-agnostic location-aware check
9328 return nai.networkCapabilities.hasTransport(TRANSPORT_WIFI);
9329 }
9330
Cody Kesting0b4be022021-05-20 22:57:07 +00009331 private boolean hasLocationPermission(String packageName, int uid) {
9332 // LocationPermissionChecker#checkLocationPermission can throw SecurityException if the uid
9333 // and package name don't match. Throwing on the CS thread is not acceptable, so wrap the
9334 // call in a try-catch.
9335 try {
9336 if (!mLocationPermissionChecker.checkLocationPermission(
9337 packageName, null /* featureId */, uid, null /* message */)) {
9338 return false;
9339 }
9340 } catch (SecurityException e) {
9341 return false;
9342 }
9343
9344 return true;
9345 }
9346
9347 private boolean ownsVpnRunningOverNetwork(int uid, Network network) {
9348 for (NetworkAgentInfo virtual : mNetworkAgentInfos) {
Treehugger Robot4703a8c2021-07-02 13:55:33 +00009349 if (virtual.propagateUnderlyingCapabilities()
Cody Kesting0b4be022021-05-20 22:57:07 +00009350 && virtual.networkCapabilities.getOwnerUid() == uid
9351 && CollectionUtils.contains(virtual.declaredUnderlyingNetworks, network)) {
9352 return true;
9353 }
9354 }
9355
9356 return false;
9357 }
9358
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00009359 @VisibleForTesting
9360 boolean checkConnectivityDiagnosticsPermissions(
9361 int callbackPid, int callbackUid, NetworkAgentInfo nai, String callbackPackageName) {
9362 if (checkNetworkStackPermission(callbackPid, callbackUid)) {
9363 return true;
9364 }
9365
Cody Kesting0b4be022021-05-20 22:57:07 +00009366 // Administrator UIDs also contains the Owner UID
9367 final int[] administratorUids = nai.networkCapabilities.getAdministratorUids();
9368 if (!CollectionUtils.contains(administratorUids, callbackUid)
9369 && !ownsVpnRunningOverNetwork(callbackUid, nai.network)) {
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00009370 return false;
9371 }
9372
Treehugger Robot27b68882021-06-07 19:42:39 +00009373 return !isLocationPermissionRequiredForConnectivityDiagnostics(nai)
9374 || hasLocationPermission(callbackPackageName, callbackUid);
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00009375 }
9376
9377 @Override
9378 public void registerConnectivityDiagnosticsCallback(
9379 @NonNull IConnectivityDiagnosticsCallback callback,
9380 @NonNull NetworkRequest request,
9381 @NonNull String callingPackageName) {
9382 if (request.legacyType != TYPE_NONE) {
9383 throw new IllegalArgumentException("ConnectivityManager.TYPE_* are deprecated."
9384 + " Please use NetworkCapabilities instead.");
9385 }
9386 final int callingUid = mDeps.getCallingUid();
9387 mAppOpsManager.checkPackage(callingUid, callingPackageName);
9388
9389 // This NetworkCapabilities is only used for matching to Networks. Clear out its owner uid
9390 // and administrator uids to be safe.
9391 final NetworkCapabilities nc = new NetworkCapabilities(request.networkCapabilities);
9392 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
9393
9394 final NetworkRequest requestWithId =
9395 new NetworkRequest(
9396 nc, TYPE_NONE, nextNetworkRequestId(), NetworkRequest.Type.LISTEN);
9397
9398 // NetworkRequestInfos created here count towards MAX_NETWORK_REQUESTS_PER_UID limit.
9399 //
9400 // nri is not bound to the death of callback. Instead, callback.bindToDeath() is set in
9401 // handleRegisterConnectivityDiagnosticsCallback(). nri will be cleaned up as part of the
9402 // callback's binder death.
9403 final NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, requestWithId);
9404 final ConnectivityDiagnosticsCallbackInfo cbInfo =
9405 new ConnectivityDiagnosticsCallbackInfo(callback, nri, callingPackageName);
9406
9407 mConnectivityDiagnosticsHandler.sendMessage(
9408 mConnectivityDiagnosticsHandler.obtainMessage(
9409 ConnectivityDiagnosticsHandler
9410 .EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
9411 cbInfo));
9412 }
9413
9414 @Override
9415 public void unregisterConnectivityDiagnosticsCallback(
9416 @NonNull IConnectivityDiagnosticsCallback callback) {
9417 Objects.requireNonNull(callback, "callback must be non-null");
9418 mConnectivityDiagnosticsHandler.sendMessage(
9419 mConnectivityDiagnosticsHandler.obtainMessage(
9420 ConnectivityDiagnosticsHandler
9421 .EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
9422 mDeps.getCallingUid(),
9423 0,
9424 callback));
9425 }
9426
9427 @Override
9428 public void simulateDataStall(int detectionMethod, long timestampMillis,
9429 @NonNull Network network, @NonNull PersistableBundle extras) {
9430 enforceAnyPermissionOf(android.Manifest.permission.MANAGE_TEST_NETWORKS,
9431 android.Manifest.permission.NETWORK_STACK);
9432 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
9433 if (!nc.hasTransport(TRANSPORT_TEST)) {
9434 throw new SecurityException("Data Stall simluation is only possible for test networks");
9435 }
9436
9437 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
9438 if (nai == null || nai.creatorUid != mDeps.getCallingUid()) {
9439 throw new SecurityException("Data Stall simulation is only possible for network "
9440 + "creators");
9441 }
9442
9443 // Instead of passing the data stall directly to the ConnectivityDiagnostics handler, treat
9444 // this as a Data Stall received directly from NetworkMonitor. This requires wrapping the
9445 // Data Stall information as a DataStallReportParcelable and passing to
9446 // #notifyDataStallSuspected. This ensures that unknown Data Stall detection methods are
9447 // still passed to ConnectivityDiagnostics (with new detection methods masked).
9448 final DataStallReportParcelable p = new DataStallReportParcelable();
9449 p.timestampMillis = timestampMillis;
9450 p.detectionMethod = detectionMethod;
9451
9452 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
9453 p.dnsConsecutiveTimeouts = extras.getInt(KEY_DNS_CONSECUTIVE_TIMEOUTS);
9454 }
9455 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
9456 p.tcpPacketFailRate = extras.getInt(KEY_TCP_PACKET_FAIL_RATE);
9457 p.tcpMetricsCollectionPeriodMillis = extras.getInt(
9458 KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS);
9459 }
9460
9461 notifyDataStallSuspected(p, network.getNetId());
9462 }
9463
9464 private class NetdCallback extends BaseNetdUnsolicitedEventListener {
9465 @Override
9466 public void onInterfaceClassActivityChanged(boolean isActive, int transportType,
9467 long timestampNs, int uid) {
9468 mNetworkActivityTracker.setAndReportNetworkActive(isActive, transportType, timestampNs);
9469 }
9470
9471 @Override
9472 public void onInterfaceLinkStateChanged(String iface, boolean up) {
9473 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
9474 nai.clatd.interfaceLinkStateChanged(iface, up);
9475 }
9476 }
9477
9478 @Override
9479 public void onInterfaceRemoved(String iface) {
9480 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
9481 nai.clatd.interfaceRemoved(iface);
9482 }
9483 }
9484 }
9485
9486 private final LegacyNetworkActivityTracker mNetworkActivityTracker;
9487
9488 /**
9489 * Class used for updating network activity tracking with netd and notify network activity
9490 * changes.
9491 */
9492 private static final class LegacyNetworkActivityTracker {
9493 private static final int NO_UID = -1;
9494 private final Context mContext;
9495 private final INetd mNetd;
9496 private final RemoteCallbackList<INetworkActivityListener> mNetworkActivityListeners =
9497 new RemoteCallbackList<>();
9498 // Indicate the current system default network activity is active or not.
9499 @GuardedBy("mActiveIdleTimers")
9500 private boolean mNetworkActive;
9501 @GuardedBy("mActiveIdleTimers")
9502 private final ArrayMap<String, IdleTimerParams> mActiveIdleTimers = new ArrayMap();
9503 private final Handler mHandler;
9504
9505 private class IdleTimerParams {
9506 public final int timeout;
9507 public final int transportType;
9508
9509 IdleTimerParams(int timeout, int transport) {
9510 this.timeout = timeout;
9511 this.transportType = transport;
9512 }
9513 }
9514
9515 LegacyNetworkActivityTracker(@NonNull Context context, @NonNull Handler handler,
9516 @NonNull INetd netd) {
9517 mContext = context;
9518 mNetd = netd;
9519 mHandler = handler;
9520 }
9521
9522 public void setAndReportNetworkActive(boolean active, int transportType, long tsNanos) {
9523 sendDataActivityBroadcast(transportTypeToLegacyType(transportType), active, tsNanos);
9524 synchronized (mActiveIdleTimers) {
9525 mNetworkActive = active;
9526 // If there are no idle timers, it means that system is not monitoring
9527 // activity, so the system default network for those default network
9528 // unspecified apps is always considered active.
9529 //
9530 // TODO: If the mActiveIdleTimers is empty, netd will actually not send
9531 // any network activity change event. Whenever this event is received,
9532 // the mActiveIdleTimers should be always not empty. The legacy behavior
9533 // is no-op. Remove to refer to mNetworkActive only.
9534 if (mNetworkActive || mActiveIdleTimers.isEmpty()) {
9535 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REPORT_NETWORK_ACTIVITY));
9536 }
9537 }
9538 }
9539
9540 // The network activity should only be updated from ConnectivityService handler thread
9541 // when mActiveIdleTimers lock is held.
9542 @GuardedBy("mActiveIdleTimers")
9543 private void reportNetworkActive() {
9544 final int length = mNetworkActivityListeners.beginBroadcast();
9545 if (DDBG) log("reportNetworkActive, notify " + length + " listeners");
9546 try {
9547 for (int i = 0; i < length; i++) {
9548 try {
9549 mNetworkActivityListeners.getBroadcastItem(i).onNetworkActive();
9550 } catch (RemoteException | RuntimeException e) {
9551 loge("Fail to send network activie to listener " + e);
9552 }
9553 }
9554 } finally {
9555 mNetworkActivityListeners.finishBroadcast();
9556 }
9557 }
9558
9559 @GuardedBy("mActiveIdleTimers")
9560 public void handleReportNetworkActivity() {
9561 synchronized (mActiveIdleTimers) {
9562 reportNetworkActive();
9563 }
9564 }
9565
9566 // This is deprecated and only to support legacy use cases.
9567 private int transportTypeToLegacyType(int type) {
9568 switch (type) {
9569 case NetworkCapabilities.TRANSPORT_CELLULAR:
9570 return TYPE_MOBILE;
9571 case NetworkCapabilities.TRANSPORT_WIFI:
9572 return TYPE_WIFI;
9573 case NetworkCapabilities.TRANSPORT_BLUETOOTH:
9574 return TYPE_BLUETOOTH;
9575 case NetworkCapabilities.TRANSPORT_ETHERNET:
9576 return TYPE_ETHERNET;
9577 default:
9578 loge("Unexpected transport in transportTypeToLegacyType: " + type);
9579 }
9580 return ConnectivityManager.TYPE_NONE;
9581 }
9582
9583 public void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
9584 final Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
9585 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
9586 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
9587 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
9588 final long ident = Binder.clearCallingIdentity();
9589 try {
9590 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
9591 RECEIVE_DATA_ACTIVITY_CHANGE,
9592 null /* resultReceiver */,
9593 null /* scheduler */,
9594 0 /* initialCode */,
9595 null /* initialData */,
9596 null /* initialExtra */);
9597 } finally {
9598 Binder.restoreCallingIdentity(ident);
9599 }
9600 }
9601
9602 /**
9603 * Setup data activity tracking for the given network.
9604 *
9605 * Every {@code setupDataActivityTracking} should be paired with a
9606 * {@link #removeDataActivityTracking} for cleanup.
9607 */
9608 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
9609 final String iface = networkAgent.linkProperties.getInterfaceName();
9610
9611 final int timeout;
9612 final int type;
9613
9614 if (networkAgent.networkCapabilities.hasTransport(
9615 NetworkCapabilities.TRANSPORT_CELLULAR)) {
9616 timeout = Settings.Global.getInt(mContext.getContentResolver(),
9617 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_MOBILE,
9618 10);
9619 type = NetworkCapabilities.TRANSPORT_CELLULAR;
9620 } else if (networkAgent.networkCapabilities.hasTransport(
9621 NetworkCapabilities.TRANSPORT_WIFI)) {
9622 timeout = Settings.Global.getInt(mContext.getContentResolver(),
9623 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_WIFI,
9624 15);
9625 type = NetworkCapabilities.TRANSPORT_WIFI;
9626 } else {
9627 return; // do not track any other networks
9628 }
9629
9630 updateRadioPowerState(true /* isActive */, type);
9631
9632 if (timeout > 0 && iface != null) {
9633 try {
9634 synchronized (mActiveIdleTimers) {
9635 // Networks start up.
9636 mNetworkActive = true;
9637 mActiveIdleTimers.put(iface, new IdleTimerParams(timeout, type));
9638 mNetd.idletimerAddInterface(iface, timeout, Integer.toString(type));
9639 reportNetworkActive();
9640 }
9641 } catch (Exception e) {
9642 // You shall not crash!
9643 loge("Exception in setupDataActivityTracking " + e);
9644 }
9645 }
9646 }
9647
9648 /**
9649 * Remove data activity tracking when network disconnects.
9650 */
9651 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
9652 final String iface = networkAgent.linkProperties.getInterfaceName();
9653 final NetworkCapabilities caps = networkAgent.networkCapabilities;
9654
9655 if (iface == null) return;
9656
9657 final int type;
9658 if (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
9659 type = NetworkCapabilities.TRANSPORT_CELLULAR;
9660 } else if (caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
9661 type = NetworkCapabilities.TRANSPORT_WIFI;
9662 } else {
9663 return; // do not track any other networks
9664 }
9665
9666 try {
9667 updateRadioPowerState(false /* isActive */, type);
9668 synchronized (mActiveIdleTimers) {
9669 final IdleTimerParams params = mActiveIdleTimers.remove(iface);
9670 // The call fails silently if no idle timer setup for this interface
9671 mNetd.idletimerRemoveInterface(iface, params.timeout,
9672 Integer.toString(params.transportType));
9673 }
9674 } catch (Exception e) {
9675 // You shall not crash!
9676 loge("Exception in removeDataActivityTracking " + e);
9677 }
9678 }
9679
9680 /**
9681 * Update data activity tracking when network state is updated.
9682 */
9683 public void updateDataActivityTracking(NetworkAgentInfo newNetwork,
9684 NetworkAgentInfo oldNetwork) {
9685 if (newNetwork != null) {
9686 setupDataActivityTracking(newNetwork);
9687 }
9688 if (oldNetwork != null) {
9689 removeDataActivityTracking(oldNetwork);
9690 }
9691 }
9692
9693 private void updateRadioPowerState(boolean isActive, int transportType) {
9694 final BatteryStatsManager bs = mContext.getSystemService(BatteryStatsManager.class);
9695 switch (transportType) {
9696 case NetworkCapabilities.TRANSPORT_CELLULAR:
9697 bs.reportMobileRadioPowerState(isActive, NO_UID);
9698 break;
9699 case NetworkCapabilities.TRANSPORT_WIFI:
9700 bs.reportWifiRadioPowerState(isActive, NO_UID);
9701 break;
9702 default:
9703 logw("Untracked transport type:" + transportType);
9704 }
9705 }
9706
9707 public boolean isDefaultNetworkActive() {
9708 synchronized (mActiveIdleTimers) {
9709 // If there are no idle timers, it means that system is not monitoring activity,
9710 // so the default network is always considered active.
9711 //
9712 // TODO : Distinguish between the cases where mActiveIdleTimers is empty because
9713 // tracking is disabled (negative idle timer value configured), or no active default
9714 // network. In the latter case, this reports active but it should report inactive.
9715 return mNetworkActive || mActiveIdleTimers.isEmpty();
9716 }
9717 }
9718
9719 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
9720 mNetworkActivityListeners.register(l);
9721 }
9722
9723 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
9724 mNetworkActivityListeners.unregister(l);
9725 }
9726
9727 public void dump(IndentingPrintWriter pw) {
9728 synchronized (mActiveIdleTimers) {
9729 pw.print("mNetworkActive="); pw.println(mNetworkActive);
9730 pw.println("Idle timers:");
9731 for (HashMap.Entry<String, IdleTimerParams> ent : mActiveIdleTimers.entrySet()) {
9732 pw.print(" "); pw.print(ent.getKey()); pw.println(":");
9733 final IdleTimerParams params = ent.getValue();
9734 pw.print(" timeout="); pw.print(params.timeout);
9735 pw.print(" type="); pw.println(params.transportType);
9736 }
9737 }
9738 }
9739 }
9740
9741 /**
9742 * Registers {@link QosSocketFilter} with {@link IQosCallback}.
9743 *
9744 * @param socketInfo the socket information
9745 * @param callback the callback to register
9746 */
9747 @Override
9748 public void registerQosSocketCallback(@NonNull final QosSocketInfo socketInfo,
9749 @NonNull final IQosCallback callback) {
9750 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(socketInfo.getNetwork());
9751 if (nai == null || nai.networkCapabilities == null) {
9752 try {
9753 callback.onError(QosCallbackException.EX_TYPE_FILTER_NETWORK_RELEASED);
9754 } catch (final RemoteException ex) {
9755 loge("registerQosCallbackInternal: RemoteException", ex);
9756 }
9757 return;
9758 }
9759 registerQosCallbackInternal(new QosSocketFilter(socketInfo), callback, nai);
9760 }
9761
9762 /**
9763 * Register a {@link IQosCallback} with base {@link QosFilter}.
9764 *
9765 * @param filter the filter to register
9766 * @param callback the callback to register
9767 * @param nai the agent information related to the filter's network
9768 */
9769 @VisibleForTesting
9770 public void registerQosCallbackInternal(@NonNull final QosFilter filter,
9771 @NonNull final IQosCallback callback, @NonNull final NetworkAgentInfo nai) {
9772 if (filter == null) throw new IllegalArgumentException("filter must be non-null");
9773 if (callback == null) throw new IllegalArgumentException("callback must be non-null");
9774
9775 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
9776 enforceConnectivityRestrictedNetworksPermission();
9777 }
9778 mQosCallbackTracker.registerCallback(callback, filter, nai);
9779 }
9780
9781 /**
9782 * Unregisters the given callback.
9783 *
9784 * @param callback the callback to unregister
9785 */
9786 @Override
9787 public void unregisterQosCallback(@NonNull final IQosCallback callback) {
9788 Objects.requireNonNull(callback, "callback must be non-null");
9789 mQosCallbackTracker.unregisterCallback(callback);
9790 }
9791
9792 // Network preference per-profile and OEM network preferences can't be set at the same
9793 // time, because it is unclear what should happen if both preferences are active for
9794 // one given UID. To make it possible, the stack would have to clarify what would happen
9795 // in case both are active at the same time. The implementation may have to be adjusted
9796 // to implement the resulting rules. For example, a priority could be defined between them,
9797 // where the OEM preference would be considered less or more important than the enterprise
9798 // preference ; this would entail implementing the priorities somehow, e.g. by doing
9799 // UID arithmetic with UID ranges or passing a priority to netd so that the routing rules
9800 // are set at the right level. Other solutions are possible, e.g. merging of the
9801 // preferences for the relevant UIDs.
9802 private static void throwConcurrentPreferenceException() {
9803 throw new IllegalStateException("Can't set NetworkPreferenceForUser and "
9804 + "set OemNetworkPreference at the same time");
9805 }
9806
9807 /**
9808 * Request that a user profile is put by default on a network matching a given preference.
9809 *
9810 * See the documentation for the individual preferences for a description of the supported
9811 * behaviors.
9812 *
9813 * @param profile the profile concerned.
9814 * @param preference the preference for this profile, as one of the PROFILE_NETWORK_PREFERENCE_*
9815 * constants.
9816 * @param listener an optional listener to listen for completion of the operation.
9817 */
9818 @Override
9819 public void setProfileNetworkPreference(@NonNull final UserHandle profile,
9820 @ConnectivityManager.ProfileNetworkPreference final int preference,
9821 @Nullable final IOnCompleteListener listener) {
9822 Objects.requireNonNull(profile);
9823 PermissionUtils.enforceNetworkStackPermission(mContext);
9824 if (DBG) {
9825 log("setProfileNetworkPreference " + profile + " to " + preference);
9826 }
9827 if (profile.getIdentifier() < 0) {
9828 throw new IllegalArgumentException("Must explicitly specify a user handle ("
9829 + "UserHandle.CURRENT not supported)");
9830 }
9831 final UserManager um = mContext.getSystemService(UserManager.class);
9832 if (!um.isManagedProfile(profile.getIdentifier())) {
9833 throw new IllegalArgumentException("Profile must be a managed profile");
9834 }
9835 // Strictly speaking, mOemNetworkPreferences should only be touched on the
9836 // handler thread. However it is an immutable object, so reading the reference is
9837 // safe - it's just possible the value is slightly outdated. For the final check,
9838 // see #handleSetProfileNetworkPreference. But if this can be caught here it is a
9839 // lot easier to understand, so opportunistically check it.
paulhu71ad4f12021-05-25 14:56:27 +08009840 // TODO: Have a priority for each preference.
9841 if (!mOemNetworkPreferences.isEmpty() || !mMobileDataPreferredUids.isEmpty()) {
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00009842 throwConcurrentPreferenceException();
9843 }
9844 final NetworkCapabilities nc;
9845 switch (preference) {
9846 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT:
9847 nc = null;
9848 break;
9849 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE:
9850 final UidRange uids = UidRange.createForUser(profile);
9851 nc = createDefaultNetworkCapabilitiesForUidRange(uids);
9852 nc.addCapability(NET_CAPABILITY_ENTERPRISE);
9853 nc.removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
9854 break;
9855 default:
9856 throw new IllegalArgumentException(
9857 "Invalid preference in setProfileNetworkPreference");
9858 }
9859 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_PROFILE_NETWORK_PREFERENCE,
9860 new Pair<>(new ProfileNetworkPreferences.Preference(profile, nc), listener)));
9861 }
9862
9863 private void validateNetworkCapabilitiesOfProfileNetworkPreference(
9864 @Nullable final NetworkCapabilities nc) {
9865 if (null == nc) return; // Null caps are always allowed. It means to remove the setting.
9866 ensureRequestableCapabilities(nc);
9867 }
9868
9869 private ArraySet<NetworkRequestInfo> createNrisFromProfileNetworkPreferences(
9870 @NonNull final ProfileNetworkPreferences prefs) {
9871 final ArraySet<NetworkRequestInfo> result = new ArraySet<>();
9872 for (final ProfileNetworkPreferences.Preference pref : prefs.preferences) {
9873 // The NRI for a user should be comprised of two layers:
9874 // - The request for the capabilities
9875 // - The request for the default network, for fallback. Create an image of it to
9876 // have the correct UIDs in it (also a request can only be part of one NRI, because
9877 // of lookups in 1:1 associations like mNetworkRequests).
9878 // Note that denying a fallback can be implemented simply by not adding the second
9879 // request.
9880 final ArrayList<NetworkRequest> nrs = new ArrayList<>();
9881 nrs.add(createNetworkRequest(NetworkRequest.Type.REQUEST, pref.capabilities));
9882 nrs.add(createDefaultInternetRequestForTransport(
9883 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
9884 setNetworkRequestUids(nrs, UidRange.fromIntRanges(pref.capabilities.getUids()));
paulhuc2198772021-05-26 15:19:20 +08009885 final NetworkRequestInfo nri = new NetworkRequestInfo(Process.myUid(), nrs,
9886 DEFAULT_NETWORK_PRIORITY_PROFILE);
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00009887 result.add(nri);
9888 }
9889 return result;
9890 }
9891
9892 private void handleSetProfileNetworkPreference(
9893 @NonNull final ProfileNetworkPreferences.Preference preference,
9894 @Nullable final IOnCompleteListener listener) {
9895 // setProfileNetworkPreference and setOemNetworkPreference are mutually exclusive, in
9896 // particular because it's not clear what preference should win in case both apply
9897 // to the same app.
9898 // The binder call has already checked this, but as mOemNetworkPreferences is only
9899 // touched on the handler thread, it's theoretically not impossible that it has changed
9900 // since.
paulhu71ad4f12021-05-25 14:56:27 +08009901 // TODO: Have a priority for each preference.
9902 if (!mOemNetworkPreferences.isEmpty() || !mMobileDataPreferredUids.isEmpty()) {
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00009903 // This may happen on a device with an OEM preference set when a user is removed.
9904 // In this case, it's safe to ignore. In particular this happens in the tests.
9905 loge("handleSetProfileNetworkPreference, but OEM network preferences not empty");
9906 return;
9907 }
9908
9909 validateNetworkCapabilitiesOfProfileNetworkPreference(preference.capabilities);
9910
9911 mProfileNetworkPreferences = mProfileNetworkPreferences.plus(preference);
9912 mSystemNetworkRequestCounter.transact(
9913 mDeps.getCallingUid(), mProfileNetworkPreferences.preferences.size(),
9914 () -> {
9915 final ArraySet<NetworkRequestInfo> nris =
9916 createNrisFromProfileNetworkPreferences(mProfileNetworkPreferences);
9917 replaceDefaultNetworkRequestsForPreference(nris);
9918 });
9919 // Finally, rematch.
9920 rematchAllNetworksAndRequests();
9921
9922 if (null != listener) {
9923 try {
9924 listener.onComplete();
9925 } catch (RemoteException e) {
9926 loge("Listener for setProfileNetworkPreference has died");
9927 }
9928 }
9929 }
9930
paulhu71ad4f12021-05-25 14:56:27 +08009931 @VisibleForTesting
9932 @NonNull
9933 ArraySet<NetworkRequestInfo> createNrisFromMobileDataPreferredUids(
9934 @NonNull final Set<Integer> uids) {
9935 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
9936 if (uids.size() == 0) {
9937 // Should not create NetworkRequestInfo if no preferences. Without uid range in
9938 // NetworkRequestInfo, makeDefaultForApps() would treat it as a illegal NRI.
9939 if (DBG) log("Don't create NetworkRequestInfo because no preferences");
9940 return nris;
9941 }
9942
9943 final List<NetworkRequest> requests = new ArrayList<>();
9944 // The NRI should be comprised of two layers:
9945 // - The request for the mobile network preferred.
9946 // - The request for the default network, for fallback.
9947 requests.add(createDefaultInternetRequestForTransport(
Paul Hu07950df2021-07-02 01:44:52 +00009948 TRANSPORT_CELLULAR, NetworkRequest.Type.REQUEST));
paulhu71ad4f12021-05-25 14:56:27 +08009949 requests.add(createDefaultInternetRequestForTransport(
9950 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
9951 final Set<UidRange> ranges = new ArraySet<>();
9952 for (final int uid : uids) {
9953 ranges.add(new UidRange(uid, uid));
9954 }
9955 setNetworkRequestUids(requests, ranges);
paulhuc2198772021-05-26 15:19:20 +08009956 nris.add(new NetworkRequestInfo(Process.myUid(), requests,
9957 DEFAULT_NETWORK_PRIORITY_MOBILE_DATA_PREFERRED));
paulhu71ad4f12021-05-25 14:56:27 +08009958 return nris;
9959 }
9960
9961 private void handleMobileDataPreferredUidsChanged() {
9962 // Ignore update preference because it's not clear what preference should win in case both
9963 // apply to the same app.
9964 // TODO: Have a priority for each preference.
9965 if (!mOemNetworkPreferences.isEmpty() || !mProfileNetworkPreferences.isEmpty()) {
9966 loge("Ignore mobile data preference change because other preferences are not empty");
9967 return;
9968 }
9969
9970 mMobileDataPreferredUids = ConnectivitySettingsManager.getMobileDataPreferredUids(mContext);
9971 mSystemNetworkRequestCounter.transact(
9972 mDeps.getCallingUid(), 1 /* numOfNewRequests */,
9973 () -> {
9974 final ArraySet<NetworkRequestInfo> nris =
9975 createNrisFromMobileDataPreferredUids(mMobileDataPreferredUids);
9976 replaceDefaultNetworkRequestsForPreference(nris);
9977 });
9978 // Finally, rematch.
9979 rematchAllNetworksAndRequests();
9980 }
9981
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00009982 private void enforceAutomotiveDevice() {
9983 final boolean isAutomotiveDevice =
9984 mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE);
9985 if (!isAutomotiveDevice) {
9986 throw new UnsupportedOperationException(
9987 "setOemNetworkPreference() is only available on automotive devices.");
9988 }
9989 }
9990
9991 /**
9992 * Used by automotive devices to set the network preferences used to direct traffic at an
9993 * application level as per the given OemNetworkPreferences. An example use-case would be an
9994 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
9995 * vehicle via a particular network.
9996 *
9997 * Calling this will overwrite the existing preference.
9998 *
9999 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
10000 * @param listener {@link ConnectivityManager.OnCompleteListener} Listener used
10001 * to communicate completion of setOemNetworkPreference();
10002 */
10003 @Override
10004 public void setOemNetworkPreference(
10005 @NonNull final OemNetworkPreferences preference,
10006 @Nullable final IOnCompleteListener listener) {
10007
James Mattisb7ca0342021-06-16 01:30:05 +000010008 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
10009 // Only bypass the permission/device checks if this is a valid test request.
10010 if (isValidTestOemNetworkPreference(preference)) {
10011 enforceManageTestNetworksPermission();
10012 } else {
10013 enforceAutomotiveDevice();
10014 enforceOemNetworkPreferencesPermission();
10015 validateOemNetworkPreferences(preference);
10016 }
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +000010017
paulhu71ad4f12021-05-25 14:56:27 +080010018 // TODO: Have a priority for each preference.
10019 if (!mProfileNetworkPreferences.isEmpty() || !mMobileDataPreferredUids.isEmpty()) {
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +000010020 // Strictly speaking, mProfileNetworkPreferences should only be touched on the
10021 // handler thread. However it is an immutable object, so reading the reference is
10022 // safe - it's just possible the value is slightly outdated. For the final check,
10023 // see #handleSetOemPreference. But if this can be caught here it is a
10024 // lot easier to understand, so opportunistically check it.
10025 throwConcurrentPreferenceException();
10026 }
10027
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +000010028 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_OEM_NETWORK_PREFERENCE,
10029 new Pair<>(preference, listener)));
10030 }
10031
James Mattisb7ca0342021-06-16 01:30:05 +000010032 /**
10033 * Check the validity of an OEM network preference to be used for testing purposes.
10034 * @param preference the preference to validate
10035 * @return true if this is a valid OEM network preference test request.
10036 */
10037 private boolean isValidTestOemNetworkPreference(
10038 @NonNull final OemNetworkPreferences preference) {
10039 // Allow for clearing of an existing OemNetworkPreference used for testing.
10040 // This isn't called on the handler thread so it is possible that mOemNetworkPreferences
10041 // changes after this check is complete. This is an unlikely scenario as calling of this API
10042 // is controlled by the OEM therefore the added complexity is not worth adding given those
10043 // circumstances. That said, it is an edge case to be aware of hence this comment.
10044 final boolean isValidTestClearPref = preference.getNetworkPreferences().size() == 0
10045 && isTestOemNetworkPreference(mOemNetworkPreferences);
10046 return isTestOemNetworkPreference(preference) || isValidTestClearPref;
10047 }
10048
10049 private boolean isTestOemNetworkPreference(@NonNull final OemNetworkPreferences preference) {
10050 final Map<String, Integer> prefMap = preference.getNetworkPreferences();
10051 return prefMap.size() == 1
10052 && (prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST)
10053 || prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST_ONLY));
10054 }
10055
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +000010056 private void validateOemNetworkPreferences(@NonNull OemNetworkPreferences preference) {
10057 for (@OemNetworkPreferences.OemNetworkPreference final int pref
10058 : preference.getNetworkPreferences().values()) {
James Mattisb7ca0342021-06-16 01:30:05 +000010059 if (pref <= 0 || OemNetworkPreferences.OEM_NETWORK_PREFERENCE_MAX < pref) {
10060 throw new IllegalArgumentException(
10061 OemNetworkPreferences.oemNetworkPreferenceToString(pref)
10062 + " is an invalid value.");
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +000010063 }
10064 }
10065 }
10066
10067 private void handleSetOemNetworkPreference(
10068 @NonNull final OemNetworkPreferences preference,
10069 @Nullable final IOnCompleteListener listener) {
10070 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
10071 if (DBG) {
10072 log("set OEM network preferences :" + preference.toString());
10073 }
10074 // setProfileNetworkPreference and setOemNetworkPreference are mutually exclusive, in
10075 // particular because it's not clear what preference should win in case both apply
10076 // to the same app.
10077 // The binder call has already checked this, but as mOemNetworkPreferences is only
10078 // touched on the handler thread, it's theoretically not impossible that it has changed
10079 // since.
paulhu71ad4f12021-05-25 14:56:27 +080010080 // TODO: Have a priority for each preference.
10081 if (!mProfileNetworkPreferences.isEmpty() || !mMobileDataPreferredUids.isEmpty()) {
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +000010082 logwtf("handleSetOemPreference, but per-profile network preferences not empty");
10083 return;
10084 }
10085
10086 mOemNetworkPreferencesLogs.log("UPDATE INITIATED: " + preference);
10087 final int uniquePreferenceCount = new ArraySet<>(
10088 preference.getNetworkPreferences().values()).size();
10089 mSystemNetworkRequestCounter.transact(
10090 mDeps.getCallingUid(), uniquePreferenceCount,
10091 () -> {
10092 final ArraySet<NetworkRequestInfo> nris =
10093 new OemNetworkRequestFactory()
10094 .createNrisFromOemNetworkPreferences(preference);
10095 replaceDefaultNetworkRequestsForPreference(nris);
10096 });
10097 mOemNetworkPreferences = preference;
10098
10099 if (null != listener) {
10100 try {
10101 listener.onComplete();
10102 } catch (RemoteException e) {
10103 loge("Can't send onComplete in handleSetOemNetworkPreference", e);
10104 }
10105 }
10106 }
10107
10108 private void replaceDefaultNetworkRequestsForPreference(
10109 @NonNull final Set<NetworkRequestInfo> nris) {
10110 // Pass in a defensive copy as this collection will be updated on remove.
10111 handleRemoveNetworkRequests(new ArraySet<>(mDefaultNetworkRequests));
10112 addPerAppDefaultNetworkRequests(nris);
10113 }
10114
10115 private void addPerAppDefaultNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
10116 ensureRunningOnConnectivityServiceThread();
10117 mDefaultNetworkRequests.addAll(nris);
10118 final ArraySet<NetworkRequestInfo> perAppCallbackRequestsToUpdate =
10119 getPerAppCallbackRequestsToUpdate();
10120 final ArraySet<NetworkRequestInfo> nrisToRegister = new ArraySet<>(nris);
10121 mSystemNetworkRequestCounter.transact(
10122 mDeps.getCallingUid(), perAppCallbackRequestsToUpdate.size(),
10123 () -> {
10124 nrisToRegister.addAll(
10125 createPerAppCallbackRequestsToRegister(perAppCallbackRequestsToUpdate));
10126 handleRemoveNetworkRequests(perAppCallbackRequestsToUpdate);
10127 handleRegisterNetworkRequests(nrisToRegister);
10128 });
10129 }
10130
10131 /**
10132 * All current requests that are tracking the default network need to be assessed as to whether
10133 * or not the current set of per-application default requests will be changing their default
10134 * network. If so, those requests will need to be updated so that they will send callbacks for
10135 * default network changes at the appropriate time. Additionally, those requests tracking the
10136 * default that were previously updated by this flow will need to be reassessed.
10137 * @return the nris which will need to be updated.
10138 */
10139 private ArraySet<NetworkRequestInfo> getPerAppCallbackRequestsToUpdate() {
10140 final ArraySet<NetworkRequestInfo> defaultCallbackRequests = new ArraySet<>();
10141 // Get the distinct nris to check since for multilayer requests, it is possible to have the
10142 // same nri in the map's values for each of its NetworkRequest objects.
10143 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>(mNetworkRequests.values());
10144 for (final NetworkRequestInfo nri : nris) {
10145 // Include this nri if it is currently being tracked.
10146 if (isPerAppTrackedNri(nri)) {
10147 defaultCallbackRequests.add(nri);
10148 continue;
10149 }
10150 // We only track callbacks for requests tracking the default.
10151 if (NetworkRequest.Type.TRACK_DEFAULT != nri.mRequests.get(0).type) {
10152 continue;
10153 }
10154 // Include this nri if it will be tracked by the new per-app default requests.
10155 final boolean isNriGoingToBeTracked =
10156 getDefaultRequestTrackingUid(nri.mAsUid) != mDefaultRequest;
10157 if (isNriGoingToBeTracked) {
10158 defaultCallbackRequests.add(nri);
10159 }
10160 }
10161 return defaultCallbackRequests;
10162 }
10163
10164 /**
10165 * Create nris for those network requests that are currently tracking the default network that
10166 * are being controlled by a per-application default.
10167 * @param perAppCallbackRequestsForUpdate the baseline network requests to be used as the
10168 * foundation when creating the nri. Important items include the calling uid's original
10169 * NetworkRequest to be used when mapping callbacks as well as the caller's uid and name. These
10170 * requests are assumed to have already been validated as needing to be updated.
10171 * @return the Set of nris to use when registering network requests.
10172 */
10173 private ArraySet<NetworkRequestInfo> createPerAppCallbackRequestsToRegister(
10174 @NonNull final ArraySet<NetworkRequestInfo> perAppCallbackRequestsForUpdate) {
10175 final ArraySet<NetworkRequestInfo> callbackRequestsToRegister = new ArraySet<>();
10176 for (final NetworkRequestInfo callbackRequest : perAppCallbackRequestsForUpdate) {
10177 final NetworkRequestInfo trackingNri =
10178 getDefaultRequestTrackingUid(callbackRequest.mAsUid);
10179
10180 // If this nri is not being tracked, the change it back to an untracked nri.
10181 if (trackingNri == mDefaultRequest) {
10182 callbackRequestsToRegister.add(new NetworkRequestInfo(
10183 callbackRequest,
10184 Collections.singletonList(callbackRequest.getNetworkRequestForCallback())));
10185 continue;
10186 }
10187
10188 final NetworkRequest request = callbackRequest.mRequests.get(0);
10189 callbackRequestsToRegister.add(new NetworkRequestInfo(
10190 callbackRequest,
10191 copyNetworkRequestsForUid(
10192 trackingNri.mRequests, callbackRequest.mAsUid,
10193 callbackRequest.mUid, request.getRequestorPackageName())));
10194 }
10195 return callbackRequestsToRegister;
10196 }
10197
10198 private static void setNetworkRequestUids(@NonNull final List<NetworkRequest> requests,
10199 @NonNull final Set<UidRange> uids) {
10200 for (final NetworkRequest req : requests) {
10201 req.networkCapabilities.setUids(UidRange.toIntRanges(uids));
10202 }
10203 }
10204
10205 /**
10206 * Class used to generate {@link NetworkRequestInfo} based off of {@link OemNetworkPreferences}.
10207 */
10208 @VisibleForTesting
10209 final class OemNetworkRequestFactory {
10210 ArraySet<NetworkRequestInfo> createNrisFromOemNetworkPreferences(
10211 @NonNull final OemNetworkPreferences preference) {
10212 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
10213 final SparseArray<Set<Integer>> uids =
10214 createUidsFromOemNetworkPreferences(preference);
10215 for (int i = 0; i < uids.size(); i++) {
10216 final int key = uids.keyAt(i);
10217 final Set<Integer> value = uids.valueAt(i);
10218 final NetworkRequestInfo nri = createNriFromOemNetworkPreferences(key, value);
10219 // No need to add an nri without any requests.
10220 if (0 == nri.mRequests.size()) {
10221 continue;
10222 }
10223 nris.add(nri);
10224 }
10225
10226 return nris;
10227 }
10228
10229 private SparseArray<Set<Integer>> createUidsFromOemNetworkPreferences(
10230 @NonNull final OemNetworkPreferences preference) {
Lorenzo Colitti659a0e12021-06-14 06:32:56 +000010231 final SparseArray<Set<Integer>> prefToUids = new SparseArray<>();
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +000010232 final PackageManager pm = mContext.getPackageManager();
10233 final List<UserHandle> users =
10234 mContext.getSystemService(UserManager.class).getUserHandles(true);
10235 if (null == users || users.size() == 0) {
10236 if (VDBG || DDBG) {
10237 log("No users currently available for setting the OEM network preference.");
10238 }
Lorenzo Colitti659a0e12021-06-14 06:32:56 +000010239 return prefToUids;
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +000010240 }
10241 for (final Map.Entry<String, Integer> entry :
10242 preference.getNetworkPreferences().entrySet()) {
10243 @OemNetworkPreferences.OemNetworkPreference final int pref = entry.getValue();
Lorenzo Colitti659a0e12021-06-14 06:32:56 +000010244 // Add the rules for all users as this policy is device wide.
10245 for (final UserHandle user : users) {
10246 try {
10247 final int uid = pm.getApplicationInfoAsUser(entry.getKey(), 0, user).uid;
10248 if (!prefToUids.contains(pref)) {
10249 prefToUids.put(pref, new ArraySet<>());
10250 }
10251 prefToUids.get(pref).add(uid);
10252 } catch (PackageManager.NameNotFoundException e) {
10253 // Although this may seem like an error scenario, it is ok that uninstalled
10254 // packages are sent on a network preference as the system will watch for
10255 // package installations associated with this network preference and update
10256 // accordingly. This is done to minimize race conditions on app install.
10257 continue;
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +000010258 }
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +000010259 }
10260 }
Lorenzo Colitti659a0e12021-06-14 06:32:56 +000010261 return prefToUids;
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +000010262 }
10263
10264 private NetworkRequestInfo createNriFromOemNetworkPreferences(
10265 @OemNetworkPreferences.OemNetworkPreference final int preference,
10266 @NonNull final Set<Integer> uids) {
10267 final List<NetworkRequest> requests = new ArrayList<>();
10268 // Requests will ultimately be evaluated by order of insertion therefore it matters.
10269 switch (preference) {
10270 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID:
10271 requests.add(createUnmeteredNetworkRequest());
10272 requests.add(createOemPaidNetworkRequest());
10273 requests.add(createDefaultInternetRequestForTransport(
10274 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
10275 break;
10276 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_NO_FALLBACK:
10277 requests.add(createUnmeteredNetworkRequest());
10278 requests.add(createOemPaidNetworkRequest());
10279 break;
10280 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_ONLY:
10281 requests.add(createOemPaidNetworkRequest());
10282 break;
10283 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PRIVATE_ONLY:
10284 requests.add(createOemPrivateNetworkRequest());
10285 break;
James Mattisb7ca0342021-06-16 01:30:05 +000010286 case OEM_NETWORK_PREFERENCE_TEST:
10287 requests.add(createUnmeteredNetworkRequest());
10288 requests.add(createTestNetworkRequest());
10289 requests.add(createDefaultRequest());
10290 break;
10291 case OEM_NETWORK_PREFERENCE_TEST_ONLY:
10292 requests.add(createTestNetworkRequest());
10293 break;
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +000010294 default:
10295 // This should never happen.
10296 throw new IllegalArgumentException("createNriFromOemNetworkPreferences()"
10297 + " called with invalid preference of " + preference);
10298 }
10299
James Mattisb7ca0342021-06-16 01:30:05 +000010300 final ArraySet<UidRange> ranges = new ArraySet<>();
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +000010301 for (final int uid : uids) {
10302 ranges.add(new UidRange(uid, uid));
10303 }
10304 setNetworkRequestUids(requests, ranges);
paulhuc2198772021-05-26 15:19:20 +080010305 return new NetworkRequestInfo(
10306 Process.myUid(), requests, DEFAULT_NETWORK_PRIORITY_OEM);
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +000010307 }
10308
10309 private NetworkRequest createUnmeteredNetworkRequest() {
10310 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
10311 .addCapability(NET_CAPABILITY_NOT_METERED)
10312 .addCapability(NET_CAPABILITY_VALIDATED);
10313 return createNetworkRequest(NetworkRequest.Type.LISTEN, netcap);
10314 }
10315
10316 private NetworkRequest createOemPaidNetworkRequest() {
10317 // NET_CAPABILITY_OEM_PAID is a restricted capability.
10318 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
10319 .addCapability(NET_CAPABILITY_OEM_PAID)
10320 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
10321 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
10322 }
10323
10324 private NetworkRequest createOemPrivateNetworkRequest() {
10325 // NET_CAPABILITY_OEM_PRIVATE is a restricted capability.
10326 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
10327 .addCapability(NET_CAPABILITY_OEM_PRIVATE)
10328 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
10329 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
10330 }
10331
10332 private NetworkCapabilities createDefaultPerAppNetCap() {
James Mattisb7ca0342021-06-16 01:30:05 +000010333 final NetworkCapabilities netcap = new NetworkCapabilities();
10334 netcap.addCapability(NET_CAPABILITY_INTERNET);
10335 netcap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
10336 return netcap;
10337 }
10338
10339 private NetworkRequest createTestNetworkRequest() {
10340 final NetworkCapabilities netcap = new NetworkCapabilities();
10341 netcap.clearAll();
10342 netcap.addTransportType(TRANSPORT_TEST);
10343 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +000010344 }
10345 }
10346}