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