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