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