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