blob: c8a0b7f0d9ae11d8197a3c972f41173e489fd7cf [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 + ")");
Chalard Jean0bad2242021-07-27 04:54:52 +00005893 // As an immutable collection, mRequests cannot change by the time the
5894 // lambda is evaluated on the handler thread so calling .get() from a binder thread
5895 // is acceptable. Use handleReleaseNetworkRequest and not directly
5896 // handleRemoveNetworkRequest so as to force a lookup in the requests map, in case
5897 // the app already unregistered the request.
5898 mHandler.post(() -> handleReleaseNetworkRequest(mRequests.get(0),
5899 mUid, false /* callOnUnavailable */));
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00005900 }
5901
5902 @Override
5903 public String toString() {
5904 final String asUidString = (mAsUid == mUid) ? "" : " asUid: " + mAsUid;
5905 return "uid/pid:" + mUid + "/" + mPid + asUidString + " activeRequest: "
5906 + (mActiveRequest == null ? null : mActiveRequest.requestId)
5907 + " callbackRequest: "
5908 + mNetworkRequestForCallback.requestId
5909 + " " + mRequests
5910 + (mPendingIntent == null ? "" : " to trigger " + mPendingIntent)
paulhude5efb92021-05-26 21:56:03 +08005911 + " callback flags: " + mCallbackFlags
5912 + " priority: " + mPreferencePriority;
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00005913 }
5914 }
5915
5916 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
5917 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
5918 if (badCapability != null) {
5919 throw new IllegalArgumentException("Cannot request network with " + badCapability);
5920 }
5921 }
5922
5923 // This checks that the passed capabilities either do not request a
5924 // specific SSID/SignalStrength, or the calling app has permission to do so.
5925 private void ensureSufficientPermissionsForRequest(NetworkCapabilities nc,
5926 int callerPid, int callerUid, String callerPackageName) {
5927 if (null != nc.getSsid() && !checkSettingsPermission(callerPid, callerUid)) {
5928 throw new SecurityException("Insufficient permissions to request a specific SSID");
5929 }
5930
5931 if (nc.hasSignalStrength()
5932 && !checkNetworkSignalStrengthWakeupPermission(callerPid, callerUid)) {
5933 throw new SecurityException(
5934 "Insufficient permissions to request a specific signal strength");
5935 }
5936 mAppOpsManager.checkPackage(callerUid, callerPackageName);
5937
5938 if (!nc.getSubscriptionIds().isEmpty()) {
5939 enforceNetworkFactoryPermission();
5940 }
5941 }
5942
5943 private int[] getSignalStrengthThresholds(@NonNull final NetworkAgentInfo nai) {
5944 final SortedSet<Integer> thresholds = new TreeSet<>();
5945 synchronized (nai) {
5946 // mNetworkRequests may contain the same value multiple times in case of
5947 // multilayer requests. It won't matter in this case because the thresholds
5948 // will then be the same and be deduplicated as they enter the `thresholds` set.
5949 // TODO : have mNetworkRequests be a Set<NetworkRequestInfo> or the like.
5950 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
5951 for (final NetworkRequest req : nri.mRequests) {
5952 if (req.networkCapabilities.hasSignalStrength()
5953 && nai.satisfiesImmutableCapabilitiesOf(req)) {
5954 thresholds.add(req.networkCapabilities.getSignalStrength());
5955 }
5956 }
5957 }
5958 }
5959 return CollectionUtils.toIntArray(new ArrayList<>(thresholds));
5960 }
5961
5962 private void updateSignalStrengthThresholds(
5963 NetworkAgentInfo nai, String reason, NetworkRequest request) {
5964 final int[] thresholdsArray = getSignalStrengthThresholds(nai);
5965
5966 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
5967 String detail;
5968 if (request != null && request.networkCapabilities.hasSignalStrength()) {
5969 detail = reason + " " + request.networkCapabilities.getSignalStrength();
5970 } else {
5971 detail = reason;
5972 }
5973 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
5974 detail, Arrays.toString(thresholdsArray), nai.toShortString()));
5975 }
5976
5977 nai.onSignalStrengthThresholdsUpdated(thresholdsArray);
5978 }
5979
5980 private void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
5981 if (nc == null) {
5982 return;
5983 }
5984 NetworkSpecifier ns = nc.getNetworkSpecifier();
5985 if (ns == null) {
5986 return;
5987 }
5988 if (ns instanceof MatchAllNetworkSpecifier) {
5989 throw new IllegalArgumentException("A MatchAllNetworkSpecifier is not permitted");
5990 }
5991 }
5992
5993 private void ensureValid(NetworkCapabilities nc) {
5994 ensureValidNetworkSpecifier(nc);
5995 if (nc.isPrivateDnsBroken()) {
5996 throw new IllegalArgumentException("Can't request broken private DNS");
5997 }
5998 }
5999
6000 private boolean isTargetSdkAtleast(int version, int callingUid,
6001 @NonNull String callingPackageName) {
6002 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
6003 final PackageManager pm =
6004 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
6005 try {
6006 final int callingVersion = pm.getTargetSdkVersion(callingPackageName);
6007 if (callingVersion < version) return false;
6008 } catch (PackageManager.NameNotFoundException e) { }
6009 return true;
6010 }
6011
6012 @Override
6013 public NetworkRequest requestNetwork(int asUid, NetworkCapabilities networkCapabilities,
6014 int reqTypeInt, Messenger messenger, int timeoutMs, IBinder binder,
6015 int legacyType, int callbackFlags, @NonNull String callingPackageName,
6016 @Nullable String callingAttributionTag) {
6017 if (legacyType != TYPE_NONE && !checkNetworkStackPermission()) {
6018 if (isTargetSdkAtleast(Build.VERSION_CODES.M, mDeps.getCallingUid(),
6019 callingPackageName)) {
6020 throw new SecurityException("Insufficient permissions to specify legacy type");
6021 }
6022 }
6023 final NetworkCapabilities defaultNc = mDefaultRequest.mRequests.get(0).networkCapabilities;
6024 final int callingUid = mDeps.getCallingUid();
6025 // Privileged callers can track the default network of another UID by passing in a UID.
6026 if (asUid != Process.INVALID_UID) {
6027 enforceSettingsPermission();
6028 } else {
6029 asUid = callingUid;
6030 }
6031 final NetworkRequest.Type reqType;
6032 try {
6033 reqType = NetworkRequest.Type.values()[reqTypeInt];
6034 } catch (ArrayIndexOutOfBoundsException e) {
6035 throw new IllegalArgumentException("Unsupported request type " + reqTypeInt);
6036 }
6037 switch (reqType) {
6038 case TRACK_DEFAULT:
6039 // If the request type is TRACK_DEFAULT, the passed {@code networkCapabilities}
6040 // is unused and will be replaced by ones appropriate for the UID (usually, the
6041 // calling app). This allows callers to keep track of the default network.
6042 networkCapabilities = copyDefaultNetworkCapabilitiesForUid(
6043 defaultNc, asUid, callingUid, callingPackageName);
6044 enforceAccessPermission();
6045 break;
6046 case TRACK_SYSTEM_DEFAULT:
6047 enforceSettingsPermission();
6048 networkCapabilities = new NetworkCapabilities(defaultNc);
6049 break;
6050 case BACKGROUND_REQUEST:
6051 enforceNetworkStackOrSettingsPermission();
6052 // Fall-through since other checks are the same with normal requests.
6053 case REQUEST:
6054 networkCapabilities = new NetworkCapabilities(networkCapabilities);
6055 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
6056 callingAttributionTag);
6057 // TODO: this is incorrect. We mark the request as metered or not depending on
6058 // the state of the app when the request is filed, but we never change the
6059 // request if the app changes network state. http://b/29964605
6060 enforceMeteredApnPolicy(networkCapabilities);
6061 break;
6062 case LISTEN_FOR_BEST:
6063 enforceAccessPermission();
6064 networkCapabilities = new NetworkCapabilities(networkCapabilities);
6065 break;
6066 default:
6067 throw new IllegalArgumentException("Unsupported request type " + reqType);
6068 }
6069 ensureRequestableCapabilities(networkCapabilities);
6070 ensureSufficientPermissionsForRequest(networkCapabilities,
6071 Binder.getCallingPid(), callingUid, callingPackageName);
6072
6073 // Enforce FOREGROUND if the caller does not have permission to use background network.
6074 if (reqType == LISTEN_FOR_BEST) {
6075 restrictBackgroundRequestForCaller(networkCapabilities);
6076 }
6077
6078 // Set the UID range for this request to the single UID of the requester, unless the
6079 // requester has the permission to specify other UIDs.
6080 // This will overwrite any allowed UIDs in the requested capabilities. Though there
6081 // are no visible methods to set the UIDs, an app could use reflection to try and get
6082 // networks for other apps so it's essential that the UIDs are overwritten.
6083 // Also set the requester UID and package name in the request.
6084 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
6085 callingUid, callingPackageName);
6086
6087 if (timeoutMs < 0) {
6088 throw new IllegalArgumentException("Bad timeout specified");
6089 }
6090 ensureValid(networkCapabilities);
6091
6092 final NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
6093 nextNetworkRequestId(), reqType);
6094 final NetworkRequestInfo nri = getNriToRegister(
6095 asUid, networkRequest, messenger, binder, callbackFlags,
6096 callingAttributionTag);
6097 if (DBG) log("requestNetwork for " + nri);
6098
6099 // For TRACK_SYSTEM_DEFAULT callbacks, the capabilities have been modified since they were
6100 // copied from the default request above. (This is necessary to ensure, for example, that
6101 // the callback does not leak sensitive information to unprivileged apps.) Check that the
6102 // changes don't alter request matching.
6103 if (reqType == NetworkRequest.Type.TRACK_SYSTEM_DEFAULT &&
6104 (!networkCapabilities.equalRequestableCapabilities(defaultNc))) {
6105 throw new IllegalStateException(
6106 "TRACK_SYSTEM_DEFAULT capabilities don't match default request: "
6107 + networkCapabilities + " vs. " + defaultNc);
6108 }
6109
6110 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
6111 if (timeoutMs > 0) {
6112 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
6113 nri), timeoutMs);
6114 }
6115 return networkRequest;
6116 }
6117
6118 /**
6119 * Return the nri to be used when registering a network request. Specifically, this is used with
6120 * requests registered to track the default request. If there is currently a per-app default
6121 * tracking the app requestor, then we need to create a version of this nri that mirrors that of
6122 * the tracking per-app default so that callbacks are sent to the app requestor appropriately.
6123 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
6124 * when a privileged caller is tracking the default network for another uid.
6125 * @param nr the network request for the nri.
6126 * @param msgr the messenger for the nri.
6127 * @param binder the binder for the nri.
6128 * @param callingAttributionTag the calling attribution tag for the nri.
6129 * @return the nri to register.
6130 */
6131 private NetworkRequestInfo getNriToRegister(final int asUid, @NonNull final NetworkRequest nr,
6132 @Nullable final Messenger msgr, @Nullable final IBinder binder,
6133 @NetworkCallback.Flag int callbackFlags,
6134 @Nullable String callingAttributionTag) {
6135 final List<NetworkRequest> requests;
6136 if (NetworkRequest.Type.TRACK_DEFAULT == nr.type) {
6137 requests = copyDefaultNetworkRequestsForUid(
6138 asUid, nr.getRequestorUid(), nr.getRequestorPackageName());
6139 } else {
6140 requests = Collections.singletonList(nr);
6141 }
6142 return new NetworkRequestInfo(
6143 asUid, requests, nr, msgr, binder, callbackFlags, callingAttributionTag);
6144 }
6145
6146 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities,
6147 String callingPackageName, String callingAttributionTag) {
6148 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
6149 enforceConnectivityRestrictedNetworksPermission();
6150 } else {
6151 enforceChangePermission(callingPackageName, callingAttributionTag);
6152 }
6153 }
6154
6155 @Override
6156 public boolean requestBandwidthUpdate(Network network) {
6157 enforceAccessPermission();
6158 NetworkAgentInfo nai = null;
6159 if (network == null) {
6160 return false;
6161 }
6162 synchronized (mNetworkForNetId) {
6163 nai = mNetworkForNetId.get(network.getNetId());
6164 }
6165 if (nai != null) {
6166 nai.onBandwidthUpdateRequested();
6167 synchronized (mBandwidthRequests) {
6168 final int uid = mDeps.getCallingUid();
6169 Integer uidReqs = mBandwidthRequests.get(uid);
6170 if (uidReqs == null) {
6171 uidReqs = 0;
6172 }
6173 mBandwidthRequests.put(uid, ++uidReqs);
6174 }
6175 return true;
6176 }
6177 return false;
6178 }
6179
6180 private boolean isSystem(int uid) {
6181 return uid < Process.FIRST_APPLICATION_UID;
6182 }
6183
6184 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
6185 final int uid = mDeps.getCallingUid();
6186 if (isSystem(uid)) {
6187 // Exemption for system uid.
6188 return;
6189 }
6190 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
6191 // Policy already enforced.
6192 return;
6193 }
6194 final long ident = Binder.clearCallingIdentity();
6195 try {
6196 if (mPolicyManager.isUidRestrictedOnMeteredNetworks(uid)) {
6197 // If UID is restricted, don't allow them to bring up metered APNs.
6198 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
6199 }
6200 } finally {
6201 Binder.restoreCallingIdentity(ident);
6202 }
6203 }
6204
6205 @Override
6206 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
6207 PendingIntent operation, @NonNull String callingPackageName,
6208 @Nullable String callingAttributionTag) {
6209 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
6210 final int callingUid = mDeps.getCallingUid();
6211 networkCapabilities = new NetworkCapabilities(networkCapabilities);
6212 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
6213 callingAttributionTag);
6214 enforceMeteredApnPolicy(networkCapabilities);
6215 ensureRequestableCapabilities(networkCapabilities);
6216 ensureSufficientPermissionsForRequest(networkCapabilities,
6217 Binder.getCallingPid(), callingUid, callingPackageName);
6218 ensureValidNetworkSpecifier(networkCapabilities);
6219 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
6220 callingUid, callingPackageName);
6221
6222 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
6223 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
6224 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
6225 callingAttributionTag);
6226 if (DBG) log("pendingRequest for " + nri);
6227 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
6228 nri));
6229 return networkRequest;
6230 }
6231
6232 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
6233 mHandler.sendMessageDelayed(
6234 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
6235 mDeps.getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
6236 }
6237
6238 @Override
6239 public void releasePendingNetworkRequest(PendingIntent operation) {
6240 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
6241 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
6242 mDeps.getCallingUid(), 0, operation));
6243 }
6244
6245 // In order to implement the compatibility measure for pre-M apps that call
6246 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
6247 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
6248 // This ensures it has permission to do so.
6249 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
6250 if (nc == null) {
6251 return false;
6252 }
6253 int[] transportTypes = nc.getTransportTypes();
6254 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
6255 return false;
6256 }
6257 try {
6258 mContext.enforceCallingOrSelfPermission(
6259 android.Manifest.permission.ACCESS_WIFI_STATE,
6260 "ConnectivityService");
6261 } catch (SecurityException e) {
6262 return false;
6263 }
6264 return true;
6265 }
6266
6267 @Override
6268 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
6269 Messenger messenger, IBinder binder,
6270 @NetworkCallback.Flag int callbackFlags,
6271 @NonNull String callingPackageName, @NonNull String callingAttributionTag) {
6272 final int callingUid = mDeps.getCallingUid();
6273 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
6274 enforceAccessPermission();
6275 }
6276
6277 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
6278 ensureSufficientPermissionsForRequest(networkCapabilities,
6279 Binder.getCallingPid(), callingUid, callingPackageName);
6280 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
6281 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
6282 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
6283 // onLost and onAvailable callbacks when networks move in and out of the background.
6284 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
6285 // can't request networks.
6286 restrictBackgroundRequestForCaller(nc);
6287 ensureValid(nc);
6288
6289 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
6290 NetworkRequest.Type.LISTEN);
6291 NetworkRequestInfo nri =
6292 new NetworkRequestInfo(callingUid, networkRequest, messenger, binder, callbackFlags,
6293 callingAttributionTag);
6294 if (VDBG) log("listenForNetwork for " + nri);
6295
6296 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
6297 return networkRequest;
6298 }
6299
6300 @Override
6301 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
6302 PendingIntent operation, @NonNull String callingPackageName,
6303 @Nullable String callingAttributionTag) {
6304 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
6305 final int callingUid = mDeps.getCallingUid();
6306 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
6307 enforceAccessPermission();
6308 }
6309 ensureValid(networkCapabilities);
6310 ensureSufficientPermissionsForRequest(networkCapabilities,
6311 Binder.getCallingPid(), callingUid, callingPackageName);
6312 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
6313 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
6314
6315 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
6316 NetworkRequest.Type.LISTEN);
6317 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
6318 callingAttributionTag);
6319 if (VDBG) log("pendingListenForNetwork for " + nri);
6320
Treehugger Robot282f7432021-06-30 21:59:16 +00006321 mHandler.sendMessage(mHandler.obtainMessage(
6322 EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT, nri));
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00006323 }
6324
6325 /** Returns the next Network provider ID. */
6326 public final int nextNetworkProviderId() {
6327 return mNextNetworkProviderId.getAndIncrement();
6328 }
6329
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00006330 @Override
6331 public void releaseNetworkRequest(NetworkRequest networkRequest) {
6332 ensureNetworkRequestHasType(networkRequest);
6333 mHandler.sendMessage(mHandler.obtainMessage(
6334 EVENT_RELEASE_NETWORK_REQUEST, mDeps.getCallingUid(), 0, networkRequest));
6335 }
6336
6337 private void handleRegisterNetworkProvider(NetworkProviderInfo npi) {
6338 if (mNetworkProviderInfos.containsKey(npi.messenger)) {
6339 // Avoid creating duplicates. even if an app makes a direct AIDL call.
6340 // This will never happen if an app calls ConnectivityManager#registerNetworkProvider,
6341 // as that will throw if a duplicate provider is registered.
6342 loge("Attempt to register existing NetworkProviderInfo "
6343 + mNetworkProviderInfos.get(npi.messenger).name);
6344 return;
6345 }
6346
6347 if (DBG) log("Got NetworkProvider Messenger for " + npi.name);
6348 mNetworkProviderInfos.put(npi.messenger, npi);
6349 npi.connect(mContext, mTrackerHandler);
6350 }
6351
6352 @Override
6353 public int registerNetworkProvider(Messenger messenger, String name) {
6354 enforceNetworkFactoryOrSettingsPermission();
6355 Objects.requireNonNull(messenger, "messenger must be non-null");
6356 NetworkProviderInfo npi = new NetworkProviderInfo(name, messenger,
6357 nextNetworkProviderId(), () -> unregisterNetworkProvider(messenger));
6358 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_PROVIDER, npi));
6359 return npi.providerId;
6360 }
6361
6362 @Override
6363 public void unregisterNetworkProvider(Messenger messenger) {
6364 enforceNetworkFactoryOrSettingsPermission();
6365 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_PROVIDER, messenger));
6366 }
6367
6368 @Override
6369 public void offerNetwork(final int providerId,
6370 @NonNull final NetworkScore score, @NonNull final NetworkCapabilities caps,
6371 @NonNull final INetworkOfferCallback callback) {
6372 Objects.requireNonNull(score);
6373 Objects.requireNonNull(caps);
6374 Objects.requireNonNull(callback);
6375 final NetworkOffer offer = new NetworkOffer(
6376 FullScore.makeProspectiveScore(score, caps), caps, callback, providerId);
6377 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_OFFER, offer));
6378 }
6379
6380 @Override
6381 public void unofferNetwork(@NonNull final INetworkOfferCallback callback) {
6382 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_OFFER, callback));
6383 }
6384
6385 private void handleUnregisterNetworkProvider(Messenger messenger) {
6386 NetworkProviderInfo npi = mNetworkProviderInfos.remove(messenger);
6387 if (npi == null) {
6388 loge("Failed to find Messenger in unregisterNetworkProvider");
6389 return;
6390 }
6391 // Unregister all the offers from this provider
6392 final ArrayList<NetworkOfferInfo> toRemove = new ArrayList<>();
6393 for (final NetworkOfferInfo noi : mNetworkOffers) {
6394 if (noi.offer.providerId == npi.providerId) {
6395 // Can't call handleUnregisterNetworkOffer here because iteration is in progress
6396 toRemove.add(noi);
6397 }
6398 }
6399 for (final NetworkOfferInfo noi : toRemove) {
6400 handleUnregisterNetworkOffer(noi);
6401 }
6402 if (DBG) log("unregisterNetworkProvider for " + npi.name);
6403 }
6404
6405 @Override
6406 public void declareNetworkRequestUnfulfillable(@NonNull final NetworkRequest request) {
6407 if (request.hasTransport(TRANSPORT_TEST)) {
6408 enforceNetworkFactoryOrTestNetworksPermission();
6409 } else {
6410 enforceNetworkFactoryPermission();
6411 }
6412 final NetworkRequestInfo nri = mNetworkRequests.get(request);
6413 if (nri != null) {
6414 // declareNetworkRequestUnfulfillable() paths don't apply to multilayer requests.
6415 ensureNotMultilayerRequest(nri, "declareNetworkRequestUnfulfillable");
6416 mHandler.post(() -> handleReleaseNetworkRequest(
6417 nri.mRequests.get(0), mDeps.getCallingUid(), true));
6418 }
6419 }
6420
6421 // NOTE: Accessed on multiple threads, must be synchronized on itself.
6422 @GuardedBy("mNetworkForNetId")
6423 private final SparseArray<NetworkAgentInfo> mNetworkForNetId = new SparseArray<>();
6424 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
6425 // An entry is first reserved with NetIdManager, prior to being added to mNetworkForNetId, so
6426 // there may not be a strict 1:1 correlation between the two.
6427 private final NetIdManager mNetIdManager;
6428
Lorenzo Colittibeb7d922021-06-09 08:33:36 +00006429 // Tracks all NetworkAgents that are currently registered.
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00006430 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
6431 private final ArraySet<NetworkAgentInfo> mNetworkAgentInfos = new ArraySet<>();
6432
6433 // UID ranges for users that are currently blocked by VPNs.
6434 // This array is accessed and iterated on multiple threads without holding locks, so its
6435 // contents must never be mutated. When the ranges change, the array is replaced with a new one
6436 // (on the handler thread).
6437 private volatile List<UidRange> mVpnBlockedUidRanges = new ArrayList<>();
6438
6439 // Must only be accessed on the handler thread
6440 @NonNull
6441 private final ArrayList<NetworkOfferInfo> mNetworkOffers = new ArrayList<>();
6442
6443 @GuardedBy("mBlockedAppUids")
6444 private final HashSet<Integer> mBlockedAppUids = new HashSet<>();
6445
6446 // Current OEM network preferences. This object must only be written to on the handler thread.
6447 // Since it is immutable and always non-null, other threads may read it if they only care
6448 // about seeing a consistent object but not that it is current.
6449 @NonNull
6450 private OemNetworkPreferences mOemNetworkPreferences =
6451 new OemNetworkPreferences.Builder().build();
6452 // Current per-profile network preferences. This object follows the same threading rules as
6453 // the OEM network preferences above.
6454 @NonNull
6455 private ProfileNetworkPreferences mProfileNetworkPreferences = new ProfileNetworkPreferences();
6456
paulhu71ad4f12021-05-25 14:56:27 +08006457 // A set of UIDs that should use mobile data preferentially if available. This object follows
6458 // the same threading rules as the OEM network preferences above.
6459 @NonNull
6460 private Set<Integer> mMobileDataPreferredUids = new ArraySet<>();
6461
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00006462 // OemNetworkPreferences activity String log entries.
6463 private static final int MAX_OEM_NETWORK_PREFERENCE_LOGS = 20;
6464 @NonNull
6465 private final LocalLog mOemNetworkPreferencesLogs =
6466 new LocalLog(MAX_OEM_NETWORK_PREFERENCE_LOGS);
6467
6468 /**
6469 * Determine whether a given package has a mapping in the current OemNetworkPreferences.
6470 * @param packageName the package name to check existence of a mapping for.
6471 * @return true if a mapping exists, false otherwise
6472 */
6473 private boolean isMappedInOemNetworkPreference(@NonNull final String packageName) {
6474 return mOemNetworkPreferences.getNetworkPreferences().containsKey(packageName);
6475 }
6476
6477 // The always-on request for an Internet-capable network that apps without a specific default
6478 // fall back to.
6479 @VisibleForTesting
6480 @NonNull
6481 final NetworkRequestInfo mDefaultRequest;
6482 // Collection of NetworkRequestInfo's used for default networks.
6483 @VisibleForTesting
6484 @NonNull
6485 final ArraySet<NetworkRequestInfo> mDefaultNetworkRequests = new ArraySet<>();
6486
6487 private boolean isPerAppDefaultRequest(@NonNull final NetworkRequestInfo nri) {
6488 return (mDefaultNetworkRequests.contains(nri) && mDefaultRequest != nri);
6489 }
6490
6491 /**
6492 * Return the default network request currently tracking the given uid.
6493 * @param uid the uid to check.
6494 * @return the NetworkRequestInfo tracking the given uid.
6495 */
6496 @NonNull
6497 private NetworkRequestInfo getDefaultRequestTrackingUid(final int uid) {
paulhude5efb92021-05-26 21:56:03 +08006498 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00006499 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00006500 // Checking the first request is sufficient as only multilayer requests will have more
6501 // than one request and for multilayer, all requests will track the same uids.
6502 if (nri.mRequests.get(0).networkCapabilities.appliesToUid(uid)) {
paulhude5efb92021-05-26 21:56:03 +08006503 // Find out the highest priority request.
6504 if (nri.hasHigherPriorityThan(highestPriorityNri)) {
6505 highestPriorityNri = nri;
6506 }
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00006507 }
6508 }
paulhude5efb92021-05-26 21:56:03 +08006509 return highestPriorityNri;
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00006510 }
6511
6512 /**
6513 * Get a copy of the network requests of the default request that is currently tracking the
6514 * given uid.
6515 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
6516 * when a privileged caller is tracking the default network for another uid.
6517 * @param requestorUid the uid to check the default for.
6518 * @param requestorPackageName the requestor's package name.
6519 * @return a copy of the default's NetworkRequest that is tracking the given uid.
6520 */
6521 @NonNull
6522 private List<NetworkRequest> copyDefaultNetworkRequestsForUid(
6523 final int asUid, final int requestorUid, @NonNull final String requestorPackageName) {
6524 return copyNetworkRequestsForUid(
6525 getDefaultRequestTrackingUid(asUid).mRequests,
6526 asUid, requestorUid, requestorPackageName);
6527 }
6528
6529 /**
6530 * Copy the given nri's NetworkRequest collection.
6531 * @param requestsToCopy the NetworkRequest collection to be copied.
6532 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
6533 * when a privileged caller is tracking the default network for another uid.
6534 * @param requestorUid the uid to set on the copied collection.
6535 * @param requestorPackageName the package name to set on the copied collection.
6536 * @return the copied NetworkRequest collection.
6537 */
6538 @NonNull
6539 private List<NetworkRequest> copyNetworkRequestsForUid(
6540 @NonNull final List<NetworkRequest> requestsToCopy, final int asUid,
6541 final int requestorUid, @NonNull final String requestorPackageName) {
6542 final List<NetworkRequest> requests = new ArrayList<>();
6543 for (final NetworkRequest nr : requestsToCopy) {
6544 requests.add(new NetworkRequest(copyDefaultNetworkCapabilitiesForUid(
6545 nr.networkCapabilities, asUid, requestorUid, requestorPackageName),
6546 nr.legacyType, nextNetworkRequestId(), nr.type));
6547 }
6548 return requests;
6549 }
6550
6551 @NonNull
6552 private NetworkCapabilities copyDefaultNetworkCapabilitiesForUid(
6553 @NonNull final NetworkCapabilities netCapToCopy, final int asUid,
6554 final int requestorUid, @NonNull final String requestorPackageName) {
6555 // These capabilities are for a TRACK_DEFAULT callback, so:
6556 // 1. Remove NET_CAPABILITY_VPN, because it's (currently!) the only difference between
6557 // mDefaultRequest and a per-UID default request.
6558 // TODO: stop depending on the fact that these two unrelated things happen to be the same
6559 // 2. Always set the UIDs to asUid. restrictRequestUidsForCallerAndSetRequestorInfo will
6560 // not do this in the case of a privileged application.
6561 final NetworkCapabilities netCap = new NetworkCapabilities(netCapToCopy);
6562 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
6563 netCap.setSingleUid(asUid);
6564 restrictRequestUidsForCallerAndSetRequestorInfo(
6565 netCap, requestorUid, requestorPackageName);
6566 return netCap;
6567 }
6568
6569 /**
6570 * Get the nri that is currently being tracked for callbacks by per-app defaults.
6571 * @param nr the network request to check for equality against.
6572 * @return the nri if one exists, null otherwise.
6573 */
6574 @Nullable
6575 private NetworkRequestInfo getNriForAppRequest(@NonNull final NetworkRequest nr) {
6576 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
6577 if (nri.getNetworkRequestForCallback().equals(nr)) {
6578 return nri;
6579 }
6580 }
6581 return null;
6582 }
6583
6584 /**
6585 * Check if an nri is currently being managed by per-app default networking.
6586 * @param nri the nri to check.
6587 * @return true if this nri is currently being managed by per-app default networking.
6588 */
6589 private boolean isPerAppTrackedNri(@NonNull final NetworkRequestInfo nri) {
6590 // nri.mRequests.get(0) is only different from the original request filed in
6591 // nri.getNetworkRequestForCallback() if nri.mRequests was changed by per-app default
6592 // functionality therefore if these two don't match, it means this particular nri is
6593 // currently being managed by a per-app default.
6594 return nri.getNetworkRequestForCallback() != nri.mRequests.get(0);
6595 }
6596
6597 /**
6598 * Determine if an nri is a managed default request that disallows default networking.
6599 * @param nri the request to evaluate
6600 * @return true if device-default networking is disallowed
6601 */
6602 private boolean isDefaultBlocked(@NonNull final NetworkRequestInfo nri) {
6603 // Check if this nri is a managed default that supports the default network at its
6604 // lowest priority request.
6605 final NetworkRequest defaultNetworkRequest = mDefaultRequest.mRequests.get(0);
6606 final NetworkCapabilities lowestPriorityNetCap =
6607 nri.mRequests.get(nri.mRequests.size() - 1).networkCapabilities;
6608 return isPerAppDefaultRequest(nri)
6609 && !(defaultNetworkRequest.networkCapabilities.equalRequestableCapabilities(
6610 lowestPriorityNetCap));
6611 }
6612
6613 // Request used to optionally keep mobile data active even when higher
6614 // priority networks like Wi-Fi are active.
6615 private final NetworkRequest mDefaultMobileDataRequest;
6616
6617 // Request used to optionally keep wifi data active even when higher
6618 // priority networks like ethernet are active.
6619 private final NetworkRequest mDefaultWifiRequest;
6620
6621 // Request used to optionally keep vehicle internal network always active
6622 private final NetworkRequest mDefaultVehicleRequest;
6623
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00006624 // Sentinel NAI used to direct apps with default networks that should have no connectivity to a
6625 // network with no service. This NAI should never be matched against, nor should any public API
6626 // ever return the associated network. For this reason, this NAI is not in the list of available
6627 // NAIs. It is used in computeNetworkReassignment() to be set as the satisfier for non-device
6628 // default requests that don't support using the device default network which will ultimately
6629 // allow ConnectivityService to use this no-service network when calling makeDefaultForApps().
6630 @VisibleForTesting
6631 final NetworkAgentInfo mNoServiceNetwork;
6632
6633 // The NetworkAgentInfo currently satisfying the default request, if any.
6634 private NetworkAgentInfo getDefaultNetwork() {
6635 return mDefaultRequest.mSatisfier;
6636 }
6637
6638 private NetworkAgentInfo getDefaultNetworkForUid(final int uid) {
paulhude5efb92021-05-26 21:56:03 +08006639 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00006640 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
6641 // Currently, all network requests will have the same uids therefore checking the first
6642 // one is sufficient. If/when uids are tracked at the nri level, this can change.
6643 final Set<UidRange> uids = nri.mRequests.get(0).networkCapabilities.getUidRanges();
6644 if (null == uids) {
6645 continue;
6646 }
6647 for (final UidRange range : uids) {
6648 if (range.contains(uid)) {
paulhude5efb92021-05-26 21:56:03 +08006649 if (nri.hasHigherPriorityThan(highestPriorityNri)) {
6650 highestPriorityNri = nri;
6651 }
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00006652 }
6653 }
6654 }
paulhude5efb92021-05-26 21:56:03 +08006655 return highestPriorityNri.getSatisfier();
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00006656 }
6657
6658 @Nullable
6659 private Network getNetwork(@Nullable NetworkAgentInfo nai) {
6660 return nai != null ? nai.network : null;
6661 }
6662
6663 private void ensureRunningOnConnectivityServiceThread() {
6664 if (mHandler.getLooper().getThread() != Thread.currentThread()) {
6665 throw new IllegalStateException(
6666 "Not running on ConnectivityService thread: "
6667 + Thread.currentThread().getName());
6668 }
6669 }
6670
6671 @VisibleForTesting
6672 protected boolean isDefaultNetwork(NetworkAgentInfo nai) {
6673 return nai == getDefaultNetwork();
6674 }
6675
6676 /**
6677 * Register a new agent with ConnectivityService to handle a network.
6678 *
6679 * @param na a reference for ConnectivityService to contact the agent asynchronously.
6680 * @param networkInfo the initial info associated with this network. It can be updated later :
6681 * see {@link #updateNetworkInfo}.
6682 * @param linkProperties the initial link properties of this network. They can be updated
6683 * later : see {@link #updateLinkProperties}.
6684 * @param networkCapabilities the initial capabilites of this network. They can be updated
6685 * later : see {@link #updateCapabilities}.
6686 * @param initialScore the initial score of the network. See
6687 * {@link NetworkAgentInfo#getCurrentScore}.
6688 * @param networkAgentConfig metadata about the network. This is never updated.
6689 * @param providerId the ID of the provider owning this NetworkAgent.
6690 * @return the network created for this agent.
6691 */
6692 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo networkInfo,
6693 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
6694 @NonNull NetworkScore initialScore, NetworkAgentConfig networkAgentConfig,
6695 int providerId) {
6696 Objects.requireNonNull(networkInfo, "networkInfo must not be null");
6697 Objects.requireNonNull(linkProperties, "linkProperties must not be null");
6698 Objects.requireNonNull(networkCapabilities, "networkCapabilities must not be null");
6699 Objects.requireNonNull(initialScore, "initialScore must not be null");
6700 Objects.requireNonNull(networkAgentConfig, "networkAgentConfig must not be null");
6701 if (networkCapabilities.hasTransport(TRANSPORT_TEST)) {
6702 enforceAnyPermissionOf(Manifest.permission.MANAGE_TEST_NETWORKS);
6703 } else {
6704 enforceNetworkFactoryPermission();
6705 }
6706
6707 final int uid = mDeps.getCallingUid();
6708 final long token = Binder.clearCallingIdentity();
6709 try {
6710 return registerNetworkAgentInternal(na, networkInfo, linkProperties,
6711 networkCapabilities, initialScore, networkAgentConfig, providerId, uid);
6712 } finally {
6713 Binder.restoreCallingIdentity(token);
6714 }
6715 }
6716
6717 private Network registerNetworkAgentInternal(INetworkAgent na, NetworkInfo networkInfo,
6718 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
6719 NetworkScore currentScore, NetworkAgentConfig networkAgentConfig, int providerId,
6720 int uid) {
6721 if (networkCapabilities.hasTransport(TRANSPORT_TEST)) {
6722 // Strictly, sanitizing here is unnecessary as the capabilities will be sanitized in
6723 // the call to mixInCapabilities below anyway, but sanitizing here means the NAI never
6724 // sees capabilities that may be malicious, which might prevent mistakes in the future.
6725 networkCapabilities = new NetworkCapabilities(networkCapabilities);
6726 networkCapabilities.restrictCapabilitesForTestNetwork(uid);
6727 }
6728
6729 LinkProperties lp = new LinkProperties(linkProperties);
6730
6731 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
6732 final NetworkAgentInfo nai = new NetworkAgentInfo(na,
6733 new Network(mNetIdManager.reserveNetId()), new NetworkInfo(networkInfo), lp, nc,
6734 currentScore, mContext, mTrackerHandler, new NetworkAgentConfig(networkAgentConfig),
6735 this, mNetd, mDnsResolver, providerId, uid, mLingerDelayMs,
6736 mQosCallbackTracker, mDeps);
6737
6738 // Make sure the LinkProperties and NetworkCapabilities reflect what the agent info says.
6739 processCapabilitiesFromAgent(nai, nc);
6740 nai.getAndSetNetworkCapabilities(mixInCapabilities(nai, nc));
6741 processLinkPropertiesFromAgent(nai, nai.linkProperties);
6742
6743 final String extraInfo = networkInfo.getExtraInfo();
6744 final String name = TextUtils.isEmpty(extraInfo)
6745 ? nai.networkCapabilities.getSsid() : extraInfo;
6746 if (DBG) log("registerNetworkAgent " + nai);
6747 mDeps.getNetworkStack().makeNetworkMonitor(
6748 nai.network, name, new NetworkMonitorCallbacks(nai));
6749 // NetworkAgentInfo registration will finish when the NetworkMonitor is created.
6750 // If the network disconnects or sends any other event before that, messages are deferred by
6751 // NetworkAgent until nai.connect(), which will be called when finalizing the
6752 // registration.
6753 return nai.network;
6754 }
6755
6756 private void handleRegisterNetworkAgent(NetworkAgentInfo nai, INetworkMonitor networkMonitor) {
6757 nai.onNetworkMonitorCreated(networkMonitor);
6758 if (VDBG) log("Got NetworkAgent Messenger");
6759 mNetworkAgentInfos.add(nai);
6760 synchronized (mNetworkForNetId) {
6761 mNetworkForNetId.put(nai.network.getNetId(), nai);
6762 }
6763
6764 try {
6765 networkMonitor.start();
6766 } catch (RemoteException e) {
6767 e.rethrowAsRuntimeException();
6768 }
6769 nai.notifyRegistered();
6770 NetworkInfo networkInfo = nai.networkInfo;
6771 updateNetworkInfo(nai, networkInfo);
6772 updateUids(nai, null, nai.networkCapabilities);
6773 }
6774
6775 private class NetworkOfferInfo implements IBinder.DeathRecipient {
6776 @NonNull public final NetworkOffer offer;
6777
6778 NetworkOfferInfo(@NonNull final NetworkOffer offer) {
6779 this.offer = offer;
6780 }
6781
6782 @Override
6783 public void binderDied() {
6784 mHandler.post(() -> handleUnregisterNetworkOffer(this));
6785 }
6786 }
6787
6788 private boolean isNetworkProviderWithIdRegistered(final int providerId) {
6789 for (final NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
6790 if (npi.providerId == providerId) return true;
6791 }
6792 return false;
6793 }
6794
6795 /**
6796 * Register or update a network offer.
6797 * @param newOffer The new offer. If the callback member is the same as an existing
6798 * offer, it is an update of that offer.
6799 */
6800 private void handleRegisterNetworkOffer(@NonNull final NetworkOffer newOffer) {
6801 ensureRunningOnConnectivityServiceThread();
6802 if (!isNetworkProviderWithIdRegistered(newOffer.providerId)) {
6803 // This may actually happen if a provider updates its score or registers and then
6804 // immediately unregisters. The offer would still be in the handler queue, but the
6805 // provider would have been removed.
6806 if (DBG) log("Received offer from an unregistered provider");
6807 return;
6808 }
6809 final NetworkOfferInfo existingOffer = findNetworkOfferInfoByCallback(newOffer.callback);
6810 if (null != existingOffer) {
6811 handleUnregisterNetworkOffer(existingOffer);
6812 newOffer.migrateFrom(existingOffer.offer);
6813 }
6814 final NetworkOfferInfo noi = new NetworkOfferInfo(newOffer);
6815 try {
6816 noi.offer.callback.asBinder().linkToDeath(noi, 0 /* flags */);
6817 } catch (RemoteException e) {
6818 noi.binderDied();
6819 return;
6820 }
6821 mNetworkOffers.add(noi);
6822 issueNetworkNeeds(noi);
6823 }
6824
6825 private void handleUnregisterNetworkOffer(@NonNull final NetworkOfferInfo noi) {
6826 ensureRunningOnConnectivityServiceThread();
6827 mNetworkOffers.remove(noi);
6828 noi.offer.callback.asBinder().unlinkToDeath(noi, 0 /* flags */);
6829 }
6830
6831 @Nullable private NetworkOfferInfo findNetworkOfferInfoByCallback(
6832 @NonNull final INetworkOfferCallback callback) {
6833 ensureRunningOnConnectivityServiceThread();
6834 for (final NetworkOfferInfo noi : mNetworkOffers) {
6835 if (noi.offer.callback.asBinder().equals(callback.asBinder())) return noi;
6836 }
6837 return null;
6838 }
6839
6840 /**
6841 * Called when receiving LinkProperties directly from a NetworkAgent.
6842 * Stores into |nai| any data coming from the agent that might also be written to the network's
6843 * LinkProperties by ConnectivityService itself. This ensures that the data provided by the
6844 * agent is not lost when updateLinkProperties is called.
6845 * This method should never alter the agent's LinkProperties, only store data in |nai|.
6846 */
6847 private void processLinkPropertiesFromAgent(NetworkAgentInfo nai, LinkProperties lp) {
6848 lp.ensureDirectlyConnectedRoutes();
6849 nai.clatd.setNat64PrefixFromRa(lp.getNat64Prefix());
6850 nai.networkAgentPortalData = lp.getCaptivePortalData();
6851 }
6852
6853 private void updateLinkProperties(NetworkAgentInfo networkAgent, @NonNull LinkProperties newLp,
6854 @NonNull LinkProperties oldLp) {
6855 int netId = networkAgent.network.getNetId();
6856
6857 // The NetworkAgent does not know whether clatd is running on its network or not, or whether
6858 // a NAT64 prefix was discovered by the DNS resolver. Before we do anything else, make sure
6859 // the LinkProperties for the network are accurate.
6860 networkAgent.clatd.fixupLinkProperties(oldLp, newLp);
6861
6862 updateInterfaces(newLp, oldLp, netId, networkAgent.networkCapabilities);
6863
6864 // update filtering rules, need to happen after the interface update so netd knows about the
6865 // new interface (the interface name -> index map becomes initialized)
6866 updateVpnFiltering(newLp, oldLp, networkAgent);
6867
6868 updateMtu(newLp, oldLp);
6869 // TODO - figure out what to do for clat
6870// for (LinkProperties lp : newLp.getStackedLinks()) {
6871// updateMtu(lp, null);
6872// }
6873 if (isDefaultNetwork(networkAgent)) {
6874 updateTcpBufferSizes(newLp.getTcpBufferSizes());
6875 }
6876
6877 updateRoutes(newLp, oldLp, netId);
6878 updateDnses(newLp, oldLp, netId);
6879 // Make sure LinkProperties represents the latest private DNS status.
6880 // This does not need to be done before updateDnses because the
6881 // LinkProperties are not the source of the private DNS configuration.
6882 // updateDnses will fetch the private DNS configuration from DnsManager.
6883 mDnsManager.updatePrivateDnsStatus(netId, newLp);
6884
6885 if (isDefaultNetwork(networkAgent)) {
6886 handleApplyDefaultProxy(newLp.getHttpProxy());
6887 } else {
6888 updateProxy(newLp, oldLp);
6889 }
6890
6891 updateWakeOnLan(newLp);
6892
6893 // Captive portal data is obtained from NetworkMonitor and stored in NetworkAgentInfo.
6894 // It is not always contained in the LinkProperties sent from NetworkAgents, and if it
6895 // does, it needs to be merged here.
6896 newLp.setCaptivePortalData(mergeCaptivePortalData(networkAgent.networkAgentPortalData,
6897 networkAgent.capportApiData));
6898
6899 // TODO - move this check to cover the whole function
6900 if (!Objects.equals(newLp, oldLp)) {
6901 synchronized (networkAgent) {
6902 networkAgent.linkProperties = newLp;
6903 }
6904 // Start or stop DNS64 detection and 464xlat according to network state.
6905 networkAgent.clatd.update();
6906 notifyIfacesChangedForNetworkStats();
6907 networkAgent.networkMonitor().notifyLinkPropertiesChanged(
6908 new LinkProperties(newLp, true /* parcelSensitiveFields */));
6909 if (networkAgent.everConnected) {
6910 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
6911 }
6912 }
6913
6914 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
6915 }
6916
6917 /**
6918 * @param naData captive portal data from NetworkAgent
6919 * @param apiData captive portal data from capport API
6920 */
6921 @Nullable
6922 private CaptivePortalData mergeCaptivePortalData(CaptivePortalData naData,
6923 CaptivePortalData apiData) {
6924 if (naData == null || apiData == null) {
6925 return naData == null ? apiData : naData;
6926 }
6927 final CaptivePortalData.Builder captivePortalBuilder =
6928 new CaptivePortalData.Builder(naData);
6929
6930 if (apiData.isCaptive()) {
6931 captivePortalBuilder.setCaptive(true);
6932 }
6933 if (apiData.isSessionExtendable()) {
6934 captivePortalBuilder.setSessionExtendable(true);
6935 }
6936 if (apiData.getExpiryTimeMillis() >= 0 || apiData.getByteLimit() >= 0) {
6937 // Expiry time, bytes remaining, refresh time all need to come from the same source,
6938 // otherwise data would be inconsistent. Prefer the capport API info if present,
6939 // as it can generally be refreshed more often.
6940 captivePortalBuilder.setExpiryTime(apiData.getExpiryTimeMillis());
6941 captivePortalBuilder.setBytesRemaining(apiData.getByteLimit());
6942 captivePortalBuilder.setRefreshTime(apiData.getRefreshTimeMillis());
6943 } else if (naData.getExpiryTimeMillis() < 0 && naData.getByteLimit() < 0) {
6944 // No source has time / bytes remaining information: surface the newest refresh time
6945 // for other fields
6946 captivePortalBuilder.setRefreshTime(
6947 Math.max(naData.getRefreshTimeMillis(), apiData.getRefreshTimeMillis()));
6948 }
6949
6950 // Prioritize the user portal URL from the network agent if the source is authenticated.
6951 if (apiData.getUserPortalUrl() != null && naData.getUserPortalUrlSource()
6952 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
6953 captivePortalBuilder.setUserPortalUrl(apiData.getUserPortalUrl(),
6954 apiData.getUserPortalUrlSource());
6955 }
6956 // Prioritize the venue information URL from the network agent if the source is
6957 // authenticated.
6958 if (apiData.getVenueInfoUrl() != null && naData.getVenueInfoUrlSource()
6959 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
6960 captivePortalBuilder.setVenueInfoUrl(apiData.getVenueInfoUrl(),
6961 apiData.getVenueInfoUrlSource());
6962 }
6963 return captivePortalBuilder.build();
6964 }
6965
6966 private void wakeupModifyInterface(String iface, NetworkCapabilities caps, boolean add) {
6967 // Marks are only available on WiFi interfaces. Checking for
6968 // marks on unsupported interfaces is harmless.
6969 if (!caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
6970 return;
6971 }
6972
6973 int mark = mResources.get().getInteger(R.integer.config_networkWakeupPacketMark);
6974 int mask = mResources.get().getInteger(R.integer.config_networkWakeupPacketMask);
6975
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00006976 // Mask/mark of zero will not detect anything interesting.
6977 // Don't install rules unless both values are nonzero.
6978 if (mark == 0 || mask == 0) {
6979 return;
6980 }
6981
6982 final String prefix = "iface:" + iface;
6983 try {
6984 if (add) {
6985 mNetd.wakeupAddInterface(iface, prefix, mark, mask);
6986 } else {
6987 mNetd.wakeupDelInterface(iface, prefix, mark, mask);
6988 }
6989 } catch (Exception e) {
6990 loge("Exception modifying wakeup packet monitoring: " + e);
6991 }
6992
6993 }
6994
6995 private void updateInterfaces(final @Nullable LinkProperties newLp,
6996 final @Nullable LinkProperties oldLp, final int netId,
6997 final @NonNull NetworkCapabilities caps) {
6998 final CompareResult<String> interfaceDiff = new CompareResult<>(
6999 oldLp != null ? oldLp.getAllInterfaceNames() : null,
7000 newLp != null ? newLp.getAllInterfaceNames() : null);
7001 if (!interfaceDiff.added.isEmpty()) {
7002 for (final String iface : interfaceDiff.added) {
7003 try {
7004 if (DBG) log("Adding iface " + iface + " to network " + netId);
7005 mNetd.networkAddInterface(netId, iface);
7006 wakeupModifyInterface(iface, caps, true);
7007 mDeps.reportNetworkInterfaceForTransports(mContext, iface,
7008 caps.getTransportTypes());
7009 } catch (Exception e) {
7010 logw("Exception adding interface: " + e);
7011 }
7012 }
7013 }
7014 for (final String iface : interfaceDiff.removed) {
7015 try {
7016 if (DBG) log("Removing iface " + iface + " from network " + netId);
7017 wakeupModifyInterface(iface, caps, false);
7018 mNetd.networkRemoveInterface(netId, iface);
7019 } catch (Exception e) {
7020 loge("Exception removing interface: " + e);
7021 }
7022 }
7023 }
7024
7025 // TODO: move to frameworks/libs/net.
7026 private RouteInfoParcel convertRouteInfo(RouteInfo route) {
7027 final String nextHop;
7028
7029 switch (route.getType()) {
7030 case RouteInfo.RTN_UNICAST:
7031 if (route.hasGateway()) {
7032 nextHop = route.getGateway().getHostAddress();
7033 } else {
7034 nextHop = INetd.NEXTHOP_NONE;
7035 }
7036 break;
7037 case RouteInfo.RTN_UNREACHABLE:
7038 nextHop = INetd.NEXTHOP_UNREACHABLE;
7039 break;
7040 case RouteInfo.RTN_THROW:
7041 nextHop = INetd.NEXTHOP_THROW;
7042 break;
7043 default:
7044 nextHop = INetd.NEXTHOP_NONE;
7045 break;
7046 }
7047
7048 final RouteInfoParcel rip = new RouteInfoParcel();
7049 rip.ifName = route.getInterface();
7050 rip.destination = route.getDestination().toString();
7051 rip.nextHop = nextHop;
7052 rip.mtu = route.getMtu();
7053
7054 return rip;
7055 }
7056
7057 /**
7058 * Have netd update routes from oldLp to newLp.
7059 * @return true if routes changed between oldLp and newLp
7060 */
7061 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
7062 // compare the route diff to determine which routes have been updated
7063 final CompareOrUpdateResult<RouteInfo.RouteKey, RouteInfo> routeDiff =
7064 new CompareOrUpdateResult<>(
7065 oldLp != null ? oldLp.getAllRoutes() : null,
7066 newLp != null ? newLp.getAllRoutes() : null,
7067 (r) -> r.getRouteKey());
7068
7069 // add routes before removing old in case it helps with continuous connectivity
7070
7071 // do this twice, adding non-next-hop routes first, then routes they are dependent on
7072 for (RouteInfo route : routeDiff.added) {
7073 if (route.hasGateway()) continue;
7074 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
7075 try {
7076 mNetd.networkAddRouteParcel(netId, convertRouteInfo(route));
7077 } catch (Exception e) {
7078 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
7079 loge("Exception in networkAddRouteParcel for non-gateway: " + e);
7080 }
7081 }
7082 }
7083 for (RouteInfo route : routeDiff.added) {
7084 if (!route.hasGateway()) continue;
7085 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
7086 try {
7087 mNetd.networkAddRouteParcel(netId, convertRouteInfo(route));
7088 } catch (Exception e) {
7089 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
7090 loge("Exception in networkAddRouteParcel for gateway: " + e);
7091 }
7092 }
7093 }
7094
7095 for (RouteInfo route : routeDiff.removed) {
7096 if (VDBG || DDBG) log("Removing Route [" + route + "] from network " + netId);
7097 try {
7098 mNetd.networkRemoveRouteParcel(netId, convertRouteInfo(route));
7099 } catch (Exception e) {
7100 loge("Exception in networkRemoveRouteParcel: " + e);
7101 }
7102 }
7103
7104 for (RouteInfo route : routeDiff.updated) {
7105 if (VDBG || DDBG) log("Updating Route [" + route + "] from network " + netId);
7106 try {
7107 mNetd.networkUpdateRouteParcel(netId, convertRouteInfo(route));
7108 } catch (Exception e) {
7109 loge("Exception in networkUpdateRouteParcel: " + e);
7110 }
7111 }
7112 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty()
7113 || !routeDiff.updated.isEmpty();
7114 }
7115
7116 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
7117 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
7118 return; // no updating necessary
7119 }
7120
7121 if (DBG) {
7122 final Collection<InetAddress> dnses = newLp.getDnsServers();
7123 log("Setting DNS servers for network " + netId + " to " + dnses);
7124 }
7125 try {
7126 mDnsManager.noteDnsServersForNetwork(netId, newLp);
7127 mDnsManager.flushVmDnsCache();
7128 } catch (Exception e) {
7129 loge("Exception in setDnsConfigurationForNetwork: " + e);
7130 }
7131 }
7132
7133 private void updateVpnFiltering(LinkProperties newLp, LinkProperties oldLp,
7134 NetworkAgentInfo nai) {
7135 final String oldIface = oldLp != null ? oldLp.getInterfaceName() : null;
7136 final String newIface = newLp != null ? newLp.getInterfaceName() : null;
7137 final boolean wasFiltering = requiresVpnIsolation(nai, nai.networkCapabilities, oldLp);
7138 final boolean needsFiltering = requiresVpnIsolation(nai, nai.networkCapabilities, newLp);
7139
7140 if (!wasFiltering && !needsFiltering) {
7141 // Nothing to do.
7142 return;
7143 }
7144
7145 if (Objects.equals(oldIface, newIface) && (wasFiltering == needsFiltering)) {
7146 // Nothing changed.
7147 return;
7148 }
7149
7150 final Set<UidRange> ranges = nai.networkCapabilities.getUidRanges();
7151 final int vpnAppUid = nai.networkCapabilities.getOwnerUid();
7152 // TODO: this create a window of opportunity for apps to receive traffic between the time
7153 // when the old rules are removed and the time when new rules are added. To fix this,
7154 // make eBPF support two allowlisted interfaces so here new rules can be added before the
7155 // old rules are being removed.
7156 if (wasFiltering) {
7157 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, ranges, vpnAppUid);
7158 }
7159 if (needsFiltering) {
7160 mPermissionMonitor.onVpnUidRangesAdded(newIface, ranges, vpnAppUid);
7161 }
7162 }
7163
7164 private void updateWakeOnLan(@NonNull LinkProperties lp) {
7165 if (mWolSupportedInterfaces == null) {
7166 mWolSupportedInterfaces = new ArraySet<>(mResources.get().getStringArray(
7167 R.array.config_wakeonlan_supported_interfaces));
7168 }
7169 lp.setWakeOnLanSupported(mWolSupportedInterfaces.contains(lp.getInterfaceName()));
7170 }
7171
7172 private int getNetworkPermission(NetworkCapabilities nc) {
7173 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
7174 return INetd.PERMISSION_SYSTEM;
7175 }
7176 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
7177 return INetd.PERMISSION_NETWORK;
7178 }
7179 return INetd.PERMISSION_NONE;
7180 }
7181
7182 private void updateNetworkPermissions(@NonNull final NetworkAgentInfo nai,
7183 @NonNull final NetworkCapabilities newNc) {
7184 final int oldPermission = getNetworkPermission(nai.networkCapabilities);
7185 final int newPermission = getNetworkPermission(newNc);
7186 if (oldPermission != newPermission && nai.created && !nai.isVPN()) {
7187 try {
7188 mNetd.networkSetPermissionForNetwork(nai.network.getNetId(), newPermission);
7189 } catch (RemoteException | ServiceSpecificException e) {
7190 loge("Exception in networkSetPermissionForNetwork: " + e);
7191 }
7192 }
7193 }
7194
7195 /**
7196 * Called when receiving NetworkCapabilities directly from a NetworkAgent.
7197 * Stores into |nai| any data coming from the agent that might also be written to the network's
7198 * NetworkCapabilities by ConnectivityService itself. This ensures that the data provided by the
7199 * agent is not lost when updateCapabilities is called.
7200 * This method should never alter the agent's NetworkCapabilities, only store data in |nai|.
7201 */
7202 private void processCapabilitiesFromAgent(NetworkAgentInfo nai, NetworkCapabilities nc) {
7203 // Note: resetting the owner UID before storing the agent capabilities in NAI means that if
7204 // the agent attempts to change the owner UID, then nai.declaredCapabilities will not
7205 // actually be the same as the capabilities sent by the agent. Still, it is safer to reset
7206 // the owner UID here and behave as if the agent had never tried to change it.
7207 if (nai.networkCapabilities.getOwnerUid() != nc.getOwnerUid()) {
7208 Log.e(TAG, nai.toShortString() + ": ignoring attempt to change owner from "
7209 + nai.networkCapabilities.getOwnerUid() + " to " + nc.getOwnerUid());
7210 nc.setOwnerUid(nai.networkCapabilities.getOwnerUid());
7211 }
7212 nai.declaredCapabilities = new NetworkCapabilities(nc);
7213 }
7214
7215 /** Modifies |newNc| based on the capabilities of |underlyingNetworks| and |agentCaps|. */
7216 @VisibleForTesting
7217 void applyUnderlyingCapabilities(@Nullable Network[] underlyingNetworks,
7218 @NonNull NetworkCapabilities agentCaps, @NonNull NetworkCapabilities newNc) {
7219 underlyingNetworks = underlyingNetworksOrDefault(
7220 agentCaps.getOwnerUid(), underlyingNetworks);
7221 long transportTypes = NetworkCapabilitiesUtils.packBits(agentCaps.getTransportTypes());
7222 int downKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
7223 int upKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
7224 // metered if any underlying is metered, or originally declared metered by the agent.
7225 boolean metered = !agentCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
7226 boolean roaming = false; // roaming if any underlying is roaming
7227 boolean congested = false; // congested if any underlying is congested
7228 boolean suspended = true; // suspended if all underlying are suspended
7229
7230 boolean hadUnderlyingNetworks = false;
7231 if (null != underlyingNetworks) {
7232 for (Network underlyingNetwork : underlyingNetworks) {
7233 final NetworkAgentInfo underlying =
7234 getNetworkAgentInfoForNetwork(underlyingNetwork);
7235 if (underlying == null) continue;
7236
7237 final NetworkCapabilities underlyingCaps = underlying.networkCapabilities;
7238 hadUnderlyingNetworks = true;
7239 for (int underlyingType : underlyingCaps.getTransportTypes()) {
7240 transportTypes |= 1L << underlyingType;
7241 }
7242
7243 // Merge capabilities of this underlying network. For bandwidth, assume the
7244 // worst case.
7245 downKbps = NetworkCapabilities.minBandwidth(downKbps,
7246 underlyingCaps.getLinkDownstreamBandwidthKbps());
7247 upKbps = NetworkCapabilities.minBandwidth(upKbps,
7248 underlyingCaps.getLinkUpstreamBandwidthKbps());
7249 // If this underlying network is metered, the VPN is metered (it may cost money
7250 // to send packets on this network).
7251 metered |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
7252 // If this underlying network is roaming, the VPN is roaming (the billing structure
7253 // is different than the usual, local one).
7254 roaming |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_ROAMING);
7255 // If this underlying network is congested, the VPN is congested (the current
7256 // condition of the network affects the performance of this network).
7257 congested |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_CONGESTED);
7258 // If this network is not suspended, the VPN is not suspended (the VPN
7259 // is able to transfer some data).
7260 suspended &= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
7261 }
7262 }
7263 if (!hadUnderlyingNetworks) {
7264 // No idea what the underlying networks are; assume reasonable defaults
7265 metered = true;
7266 roaming = false;
7267 congested = false;
7268 suspended = false;
7269 }
7270
7271 newNc.setTransportTypes(NetworkCapabilitiesUtils.unpackBits(transportTypes));
7272 newNc.setLinkDownstreamBandwidthKbps(downKbps);
7273 newNc.setLinkUpstreamBandwidthKbps(upKbps);
7274 newNc.setCapability(NET_CAPABILITY_NOT_METERED, !metered);
7275 newNc.setCapability(NET_CAPABILITY_NOT_ROAMING, !roaming);
7276 newNc.setCapability(NET_CAPABILITY_NOT_CONGESTED, !congested);
7277 newNc.setCapability(NET_CAPABILITY_NOT_SUSPENDED, !suspended);
7278 }
7279
7280 /**
7281 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
7282 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
7283 * and foreground status).
7284 */
7285 @NonNull
7286 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
7287 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
7288 // Don't complain for VPNs since they're not driven by requests and there is no risk of
7289 // causing a connect/teardown loop.
7290 // TODO: remove this altogether and make it the responsibility of the NetworkProviders to
7291 // avoid connect/teardown loops.
7292 if (nai.everConnected &&
7293 !nai.isVPN() &&
7294 !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
7295 // TODO: consider not complaining when a network agent degrades its capabilities if this
7296 // does not cause any request (that is not a listen) currently matching that agent to
7297 // stop being matched by the updated agent.
7298 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
7299 if (!TextUtils.isEmpty(diff)) {
7300 Log.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
7301 }
7302 }
7303
7304 // Don't modify caller's NetworkCapabilities.
7305 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
7306 if (nai.lastValidated) {
7307 newNc.addCapability(NET_CAPABILITY_VALIDATED);
7308 } else {
7309 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
7310 }
7311 if (nai.lastCaptivePortalDetected) {
7312 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
7313 } else {
7314 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
7315 }
7316 if (nai.isBackgroundNetwork()) {
7317 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
7318 } else {
7319 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
7320 }
7321 if (nai.partialConnectivity) {
7322 newNc.addCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
7323 } else {
7324 newNc.removeCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
7325 }
7326 newNc.setPrivateDnsBroken(nai.networkCapabilities.isPrivateDnsBroken());
7327
7328 // TODO : remove this once all factories are updated to send NOT_SUSPENDED and NOT_ROAMING
7329 if (!newNc.hasTransport(TRANSPORT_CELLULAR)) {
7330 newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
7331 newNc.addCapability(NET_CAPABILITY_NOT_ROAMING);
7332 }
7333
Treehugger Robot4703a8c2021-07-02 13:55:33 +00007334 if (nai.propagateUnderlyingCapabilities()) {
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00007335 applyUnderlyingCapabilities(nai.declaredUnderlyingNetworks, nai.declaredCapabilities,
7336 newNc);
7337 }
7338
7339 return newNc;
7340 }
7341
7342 private void updateNetworkInfoForRoamingAndSuspended(NetworkAgentInfo nai,
7343 NetworkCapabilities prevNc, NetworkCapabilities newNc) {
7344 final boolean prevSuspended = !prevNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
7345 final boolean suspended = !newNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
7346 final boolean prevRoaming = !prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
7347 final boolean roaming = !newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
7348 if (prevSuspended != suspended) {
7349 // TODO (b/73132094) : remove this call once the few users of onSuspended and
7350 // onResumed have been removed.
7351 notifyNetworkCallbacks(nai, suspended ? ConnectivityManager.CALLBACK_SUSPENDED
7352 : ConnectivityManager.CALLBACK_RESUMED);
7353 }
7354 if (prevSuspended != suspended || prevRoaming != roaming) {
7355 // updateNetworkInfo will mix in the suspended info from the capabilities and
7356 // take appropriate action for the network having possibly changed state.
7357 updateNetworkInfo(nai, nai.networkInfo);
7358 }
7359 }
7360
7361 /**
7362 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
7363 *
7364 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
7365 * capabilities we manage and store in {@code nai}, such as validated status and captive
7366 * portal status)
7367 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
7368 * potentially triggers rematches.
7369 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
7370 * change.)
7371 *
7372 * @param oldScore score of the network before any of the changes that prompted us
7373 * to call this function.
7374 * @param nai the network having its capabilities updated.
7375 * @param nc the new network capabilities.
7376 */
7377 private void updateCapabilities(final int oldScore, @NonNull final NetworkAgentInfo nai,
7378 @NonNull final NetworkCapabilities nc) {
7379 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
7380 if (Objects.equals(nai.networkCapabilities, newNc)) return;
7381 updateNetworkPermissions(nai, newNc);
7382 final NetworkCapabilities prevNc = nai.getAndSetNetworkCapabilities(newNc);
7383
7384 updateUids(nai, prevNc, newNc);
7385 nai.updateScoreForNetworkAgentUpdate();
7386
7387 if (nai.getCurrentScore() == oldScore && newNc.equalRequestableCapabilities(prevNc)) {
7388 // If the requestable capabilities haven't changed, and the score hasn't changed, then
7389 // the change we're processing can't affect any requests, it can only affect the listens
7390 // on this network. We might have been called by rematchNetworkAndRequests when a
7391 // network changed foreground state.
7392 processListenRequests(nai);
7393 } else {
7394 // If the requestable capabilities have changed or the score changed, we can't have been
7395 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
7396 rematchAllNetworksAndRequests();
7397 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
7398 }
7399 updateNetworkInfoForRoamingAndSuspended(nai, prevNc, newNc);
7400
7401 final boolean oldMetered = prevNc.isMetered();
7402 final boolean newMetered = newNc.isMetered();
7403 final boolean meteredChanged = oldMetered != newMetered;
7404
7405 if (meteredChanged) {
7406 maybeNotifyNetworkBlocked(nai, oldMetered, newMetered,
7407 mVpnBlockedUidRanges, mVpnBlockedUidRanges);
7408 }
7409
7410 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING)
7411 != newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
7412
7413 // Report changes that are interesting for network statistics tracking.
7414 if (meteredChanged || roamingChanged) {
7415 notifyIfacesChangedForNetworkStats();
7416 }
7417
7418 // This network might have been underlying another network. Propagate its capabilities.
7419 propagateUnderlyingNetworkCapabilities(nai.network);
7420
7421 if (!newNc.equalsTransportTypes(prevNc)) {
7422 mDnsManager.updateTransportsForNetwork(
7423 nai.network.getNetId(), newNc.getTransportTypes());
7424 }
Lucas Lin950a65f2021-06-15 09:28:16 +00007425
7426 maybeSendProxyBroadcast(nai, prevNc, newNc);
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00007427 }
7428
7429 /** Convenience method to update the capabilities for a given network. */
7430 private void updateCapabilitiesForNetwork(NetworkAgentInfo nai) {
7431 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
7432 }
7433
7434 /**
7435 * Returns whether VPN isolation (ingress interface filtering) should be applied on the given
7436 * network.
7437 *
7438 * Ingress interface filtering enforces that all apps under the given network can only receive
7439 * packets from the network's interface (and loopback). This is important for VPNs because
7440 * apps that cannot bypass a fully-routed VPN shouldn't be able to receive packets from any
7441 * non-VPN interfaces.
7442 *
7443 * As a result, this method should return true iff
7444 * 1. the network is an app VPN (not legacy VPN)
7445 * 2. the VPN does not allow bypass
7446 * 3. the VPN is fully-routed
7447 * 4. the VPN interface is non-null
7448 *
7449 * @see INetd#firewallAddUidInterfaceRules
7450 * @see INetd#firewallRemoveUidInterfaceRules
7451 */
7452 private boolean requiresVpnIsolation(@NonNull NetworkAgentInfo nai, NetworkCapabilities nc,
7453 LinkProperties lp) {
7454 if (nc == null || lp == null) return false;
7455 return nai.isVPN()
7456 && !nai.networkAgentConfig.allowBypass
7457 && nc.getOwnerUid() != Process.SYSTEM_UID
7458 && lp.getInterfaceName() != null
7459 && (lp.hasIpv4DefaultRoute() || lp.hasIpv4UnreachableDefaultRoute())
7460 && (lp.hasIpv6DefaultRoute() || lp.hasIpv6UnreachableDefaultRoute());
7461 }
7462
7463 private static UidRangeParcel[] toUidRangeStableParcels(final @NonNull Set<UidRange> ranges) {
7464 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.size()];
7465 int index = 0;
7466 for (UidRange range : ranges) {
7467 stableRanges[index] = new UidRangeParcel(range.start, range.stop);
7468 index++;
7469 }
7470 return stableRanges;
7471 }
7472
7473 private static UidRangeParcel[] toUidRangeStableParcels(UidRange[] ranges) {
7474 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.length];
7475 for (int i = 0; i < ranges.length; i++) {
7476 stableRanges[i] = new UidRangeParcel(ranges[i].start, ranges[i].stop);
7477 }
7478 return stableRanges;
7479 }
7480
7481 private void maybeCloseSockets(NetworkAgentInfo nai, UidRangeParcel[] ranges,
7482 int[] exemptUids) {
7483 if (nai.isVPN() && !nai.networkAgentConfig.allowBypass) {
7484 try {
7485 mNetd.socketDestroy(ranges, exemptUids);
7486 } catch (Exception e) {
7487 loge("Exception in socket destroy: ", e);
7488 }
7489 }
7490 }
7491
paulhude5efb92021-05-26 21:56:03 +08007492 private void updateVpnUidRanges(boolean add, NetworkAgentInfo nai, Set<UidRange> uidRanges) {
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00007493 int[] exemptUids = new int[2];
7494 // TODO: Excluding VPN_UID is necessary in order to not to kill the TCP connection used
7495 // by PPTP. Fix this by making Vpn set the owner UID to VPN_UID instead of system when
7496 // starting a legacy VPN, and remove VPN_UID here. (b/176542831)
7497 exemptUids[0] = VPN_UID;
7498 exemptUids[1] = nai.networkCapabilities.getOwnerUid();
7499 UidRangeParcel[] ranges = toUidRangeStableParcels(uidRanges);
7500
7501 maybeCloseSockets(nai, ranges, exemptUids);
7502 try {
7503 if (add) {
paulhude2a2392021-06-09 16:11:35 +08007504 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
paulhude5efb92021-05-26 21:56:03 +08007505 nai.network.netId, ranges, PREFERENCE_PRIORITY_VPN));
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00007506 } else {
paulhude2a2392021-06-09 16:11:35 +08007507 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
paulhude5efb92021-05-26 21:56:03 +08007508 nai.network.netId, ranges, PREFERENCE_PRIORITY_VPN));
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00007509 }
7510 } catch (Exception e) {
7511 loge("Exception while " + (add ? "adding" : "removing") + " uid ranges " + uidRanges +
7512 " on netId " + nai.network.netId + ". " + e);
7513 }
7514 maybeCloseSockets(nai, ranges, exemptUids);
7515 }
7516
Lucas Lin950a65f2021-06-15 09:28:16 +00007517 private boolean isProxySetOnAnyDefaultNetwork() {
7518 ensureRunningOnConnectivityServiceThread();
7519 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
7520 final NetworkAgentInfo nai = nri.getSatisfier();
7521 if (nai != null && nai.linkProperties.getHttpProxy() != null) {
7522 return true;
7523 }
7524 }
7525 return false;
7526 }
7527
7528 private void maybeSendProxyBroadcast(NetworkAgentInfo nai, NetworkCapabilities prevNc,
7529 NetworkCapabilities newNc) {
7530 // When the apps moved from/to a VPN, a proxy broadcast is needed to inform the apps that
7531 // the proxy might be changed since the default network satisfied by the apps might also
7532 // changed.
7533 // TODO: Try to track the default network that apps use and only send a proxy broadcast when
7534 // that happens to prevent false alarms.
7535 if (nai.isVPN() && nai.everConnected && !NetworkCapabilities.hasSameUids(prevNc, newNc)
7536 && (nai.linkProperties.getHttpProxy() != null || isProxySetOnAnyDefaultNetwork())) {
7537 mProxyTracker.sendProxyBroadcast();
7538 }
7539 }
7540
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00007541 private void updateUids(NetworkAgentInfo nai, NetworkCapabilities prevNc,
7542 NetworkCapabilities newNc) {
7543 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUidRanges();
7544 Set<UidRange> newRanges = null == newNc ? null : newNc.getUidRanges();
7545 if (null == prevRanges) prevRanges = new ArraySet<>();
7546 if (null == newRanges) newRanges = new ArraySet<>();
7547 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
7548
7549 prevRanges.removeAll(newRanges);
7550 newRanges.removeAll(prevRangesCopy);
7551
7552 try {
7553 // When updating the VPN uid routing rules, add the new range first then remove the old
7554 // range. If old range were removed first, there would be a window between the old
7555 // range being removed and the new range being added, during which UIDs contained
7556 // in both ranges are not subject to any VPN routing rules. Adding new range before
7557 // removing old range works because, unlike the filtering rules below, it's possible to
7558 // add duplicate UID routing rules.
7559 // TODO: calculate the intersection of add & remove. Imagining that we are trying to
7560 // remove uid 3 from a set containing 1-5. Intersection of the prev and new sets is:
7561 // [1-5] & [1-2],[4-5] == [3]
7562 // Then we can do:
7563 // maybeCloseSockets([3])
7564 // mNetd.networkAddUidRanges([1-2],[4-5])
7565 // mNetd.networkRemoveUidRanges([1-5])
7566 // maybeCloseSockets([3])
7567 // This can prevent the sockets of uid 1-2, 4-5 from being closed. It also reduce the
7568 // number of binder calls from 6 to 4.
7569 if (!newRanges.isEmpty()) {
paulhude5efb92021-05-26 21:56:03 +08007570 updateVpnUidRanges(true, nai, newRanges);
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00007571 }
7572 if (!prevRanges.isEmpty()) {
paulhude5efb92021-05-26 21:56:03 +08007573 updateVpnUidRanges(false, nai, prevRanges);
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00007574 }
7575 final boolean wasFiltering = requiresVpnIsolation(nai, prevNc, nai.linkProperties);
7576 final boolean shouldFilter = requiresVpnIsolation(nai, newNc, nai.linkProperties);
7577 final String iface = nai.linkProperties.getInterfaceName();
7578 // For VPN uid interface filtering, old ranges need to be removed before new ranges can
7579 // be added, due to the range being expanded and stored as individual UIDs. For example
7580 // the UIDs might be updated from [0, 99999] to ([0, 10012], [10014, 99999]) which means
7581 // prevRanges = [0, 99999] while newRanges = [0, 10012], [10014, 99999]. If prevRanges
7582 // were added first and then newRanges got removed later, there would be only one uid
7583 // 10013 left. A consequence of removing old ranges before adding new ranges is that
7584 // there is now a window of opportunity when the UIDs are not subject to any filtering.
7585 // Note that this is in contrast with the (more robust) update of VPN routing rules
7586 // above, where the addition of new ranges happens before the removal of old ranges.
7587 // TODO Fix this window by computing an accurate diff on Set<UidRange>, so the old range
7588 // to be removed will never overlap with the new range to be added.
7589 if (wasFiltering && !prevRanges.isEmpty()) {
7590 mPermissionMonitor.onVpnUidRangesRemoved(iface, prevRanges, prevNc.getOwnerUid());
7591 }
7592 if (shouldFilter && !newRanges.isEmpty()) {
7593 mPermissionMonitor.onVpnUidRangesAdded(iface, newRanges, newNc.getOwnerUid());
7594 }
7595 } catch (Exception e) {
7596 // Never crash!
7597 loge("Exception in updateUids: ", e);
7598 }
7599 }
7600
7601 public void handleUpdateLinkProperties(NetworkAgentInfo nai, LinkProperties newLp) {
7602 ensureRunningOnConnectivityServiceThread();
7603
Lorenzo Colittibeb7d922021-06-09 08:33:36 +00007604 if (!mNetworkAgentInfos.contains(nai)) {
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00007605 // Ignore updates for disconnected networks
7606 return;
7607 }
7608 if (VDBG || DDBG) {
7609 log("Update of LinkProperties for " + nai.toShortString()
7610 + "; created=" + nai.created
7611 + "; everConnected=" + nai.everConnected);
7612 }
7613 // TODO: eliminate this defensive copy after confirming that updateLinkProperties does not
7614 // modify its oldLp parameter.
7615 updateLinkProperties(nai, newLp, new LinkProperties(nai.linkProperties));
7616 }
7617
7618 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
7619 int notificationType) {
7620 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
7621 Intent intent = new Intent();
7622 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
7623 // If apps could file multi-layer requests with PendingIntents, they'd need to know
7624 // which of the layer is satisfied alongside with some ID for the request. Hence, if
7625 // such an API is ever implemented, there is no doubt the right request to send in
Remi NGUYEN VAN4cb61892021-06-28 07:27:47 +00007626 // EXTRA_NETWORK_REQUEST is the active request, and whatever ID would be added would
7627 // need to be sent as a separate extra.
7628 final NetworkRequest req = nri.isMultilayerRequest()
7629 ? nri.getActiveRequest()
7630 // Non-multilayer listen requests do not have an active request
7631 : nri.mRequests.get(0);
7632 if (req == null) {
7633 Log.wtf(TAG, "No request in NRI " + nri);
7634 }
7635 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, req);
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00007636 nri.mPendingIntentSent = true;
7637 sendIntent(nri.mPendingIntent, intent);
7638 }
7639 // else not handled
7640 }
7641
7642 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
7643 mPendingIntentWakeLock.acquire();
7644 try {
7645 if (DBG) log("Sending " + pendingIntent);
7646 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
7647 } catch (PendingIntent.CanceledException e) {
7648 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
7649 mPendingIntentWakeLock.release();
7650 releasePendingNetworkRequest(pendingIntent);
7651 }
7652 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
7653 }
7654
7655 @Override
7656 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
7657 String resultData, Bundle resultExtras) {
7658 if (DBG) log("Finished sending " + pendingIntent);
7659 mPendingIntentWakeLock.release();
7660 // Release with a delay so the receiving client has an opportunity to put in its
7661 // own request.
7662 releasePendingNetworkRequestWithDelay(pendingIntent);
7663 }
7664
7665 private void callCallbackForRequest(@NonNull final NetworkRequestInfo nri,
7666 @NonNull final NetworkAgentInfo networkAgent, final int notificationType,
7667 final int arg1) {
7668 if (nri.mMessenger == null) {
7669 // Default request has no msgr. Also prevents callbacks from being invoked for
7670 // NetworkRequestInfos registered with ConnectivityDiagnostics requests. Those callbacks
7671 // are Type.LISTEN, but should not have NetworkCallbacks invoked.
7672 return;
7673 }
7674 Bundle bundle = new Bundle();
7675 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
7676 // TODO: check if defensive copies of data is needed.
7677 final NetworkRequest nrForCallback = nri.getNetworkRequestForCallback();
7678 putParcelable(bundle, nrForCallback);
7679 Message msg = Message.obtain();
7680 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
7681 putParcelable(bundle, networkAgent.network);
7682 }
7683 final boolean includeLocationSensitiveInfo =
7684 (nri.mCallbackFlags & NetworkCallback.FLAG_INCLUDE_LOCATION_INFO) != 0;
7685 switch (notificationType) {
7686 case ConnectivityManager.CALLBACK_AVAILABLE: {
7687 final NetworkCapabilities nc =
7688 networkCapabilitiesRestrictedForCallerPermissions(
7689 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
7690 putParcelable(
7691 bundle,
7692 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
7693 nc, includeLocationSensitiveInfo, nri.mPid, nri.mUid,
7694 nrForCallback.getRequestorPackageName(),
7695 nri.mCallingAttributionTag));
7696 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
7697 networkAgent.linkProperties, nri.mPid, nri.mUid));
7698 // For this notification, arg1 contains the blocked status.
7699 msg.arg1 = arg1;
7700 break;
7701 }
7702 case ConnectivityManager.CALLBACK_LOSING: {
7703 msg.arg1 = arg1;
7704 break;
7705 }
7706 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
7707 // networkAgent can't be null as it has been accessed a few lines above.
7708 final NetworkCapabilities netCap =
7709 networkCapabilitiesRestrictedForCallerPermissions(
7710 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
7711 putParcelable(
7712 bundle,
7713 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
7714 netCap, includeLocationSensitiveInfo, nri.mPid, nri.mUid,
7715 nrForCallback.getRequestorPackageName(),
7716 nri.mCallingAttributionTag));
7717 break;
7718 }
7719 case ConnectivityManager.CALLBACK_IP_CHANGED: {
7720 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
7721 networkAgent.linkProperties, nri.mPid, nri.mUid));
7722 break;
7723 }
7724 case ConnectivityManager.CALLBACK_BLK_CHANGED: {
7725 maybeLogBlockedStatusChanged(nri, networkAgent.network, arg1);
7726 msg.arg1 = arg1;
7727 break;
7728 }
7729 }
7730 msg.what = notificationType;
7731 msg.setData(bundle);
7732 try {
7733 if (VDBG) {
7734 String notification = ConnectivityManager.getCallbackName(notificationType);
7735 log("sending notification " + notification + " for " + nrForCallback);
7736 }
7737 nri.mMessenger.send(msg);
7738 } catch (RemoteException e) {
7739 // may occur naturally in the race of binder death.
7740 loge("RemoteException caught trying to send a callback msg for " + nrForCallback);
7741 }
7742 }
7743
7744 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
7745 bundle.putParcelable(t.getClass().getSimpleName(), t);
7746 }
7747
7748 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
7749 if (nai.numRequestNetworkRequests() != 0) {
7750 for (int i = 0; i < nai.numNetworkRequests(); i++) {
7751 NetworkRequest nr = nai.requestAt(i);
7752 // Ignore listening and track default requests.
7753 if (!nr.isRequest()) continue;
7754 loge("Dead network still had at least " + nr);
7755 break;
7756 }
7757 }
7758 nai.disconnect();
7759 }
7760
7761 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
7762 if (oldNetwork == null) {
7763 loge("Unknown NetworkAgentInfo in handleLingerComplete");
7764 return;
7765 }
7766 if (DBG) log("handleLingerComplete for " + oldNetwork.toShortString());
7767
7768 // If we get here it means that the last linger timeout for this network expired. So there
7769 // must be no other active linger timers, and we must stop lingering.
7770 oldNetwork.clearInactivityState();
7771
7772 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
7773 // Tear the network down.
7774 teardownUnneededNetwork(oldNetwork);
7775 } else {
7776 // Put the network in the background if it doesn't satisfy any foreground request.
7777 updateCapabilitiesForNetwork(oldNetwork);
7778 }
7779 }
7780
7781 private void processDefaultNetworkChanges(@NonNull final NetworkReassignment changes) {
7782 boolean isDefaultChanged = false;
7783 for (final NetworkRequestInfo defaultRequestInfo : mDefaultNetworkRequests) {
7784 final NetworkReassignment.RequestReassignment reassignment =
7785 changes.getReassignment(defaultRequestInfo);
7786 if (null == reassignment) {
7787 continue;
7788 }
7789 // reassignment only contains those instances where the satisfying network changed.
7790 isDefaultChanged = true;
7791 // Notify system services of the new default.
7792 makeDefault(defaultRequestInfo, reassignment.mOldNetwork, reassignment.mNewNetwork);
7793 }
7794
7795 if (isDefaultChanged) {
7796 // Hold a wakelock for a short time to help apps in migrating to a new default.
7797 scheduleReleaseNetworkTransitionWakelock();
7798 }
7799 }
7800
7801 private void makeDefault(@NonNull final NetworkRequestInfo nri,
7802 @Nullable final NetworkAgentInfo oldDefaultNetwork,
7803 @Nullable final NetworkAgentInfo newDefaultNetwork) {
7804 if (DBG) {
7805 log("Switching to new default network for: " + nri + " using " + newDefaultNetwork);
7806 }
7807
7808 // Fix up the NetworkCapabilities of any networks that have this network as underlying.
7809 if (newDefaultNetwork != null) {
7810 propagateUnderlyingNetworkCapabilities(newDefaultNetwork.network);
7811 }
7812
7813 // Set an app level managed default and return since further processing only applies to the
7814 // default network.
7815 if (mDefaultRequest != nri) {
7816 makeDefaultForApps(nri, oldDefaultNetwork, newDefaultNetwork);
7817 return;
7818 }
7819
7820 makeDefaultNetwork(newDefaultNetwork);
7821
7822 if (oldDefaultNetwork != null) {
7823 mLingerMonitor.noteLingerDefaultNetwork(oldDefaultNetwork, newDefaultNetwork);
7824 }
7825 mNetworkActivityTracker.updateDataActivityTracking(newDefaultNetwork, oldDefaultNetwork);
7826 handleApplyDefaultProxy(null != newDefaultNetwork
7827 ? newDefaultNetwork.linkProperties.getHttpProxy() : null);
7828 updateTcpBufferSizes(null != newDefaultNetwork
7829 ? newDefaultNetwork.linkProperties.getTcpBufferSizes() : null);
7830 notifyIfacesChangedForNetworkStats();
7831 }
7832
7833 private void makeDefaultForApps(@NonNull final NetworkRequestInfo nri,
7834 @Nullable final NetworkAgentInfo oldDefaultNetwork,
7835 @Nullable final NetworkAgentInfo newDefaultNetwork) {
7836 try {
7837 if (VDBG) {
7838 log("Setting default network for " + nri
7839 + " using UIDs " + nri.getUids()
7840 + " with old network " + (oldDefaultNetwork != null
7841 ? oldDefaultNetwork.network().getNetId() : "null")
7842 + " and new network " + (newDefaultNetwork != null
7843 ? newDefaultNetwork.network().getNetId() : "null"));
7844 }
7845 if (nri.getUids().isEmpty()) {
7846 throw new IllegalStateException("makeDefaultForApps called without specifying"
7847 + " any applications to set as the default." + nri);
7848 }
7849 if (null != newDefaultNetwork) {
paulhude2a2392021-06-09 16:11:35 +08007850 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00007851 newDefaultNetwork.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 if (null != oldDefaultNetwork) {
paulhude2a2392021-06-09 16:11:35 +08007856 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00007857 oldDefaultNetwork.network.getNetId(),
paulhude2a2392021-06-09 16:11:35 +08007858 toUidRangeStableParcels(nri.getUids()),
paulhude5efb92021-05-26 21:56:03 +08007859 nri.getPriorityForNetd()));
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00007860 }
7861 } catch (RemoteException | ServiceSpecificException e) {
7862 loge("Exception setting app default network", e);
7863 }
7864 }
7865
7866 private void makeDefaultNetwork(@Nullable final NetworkAgentInfo newDefaultNetwork) {
7867 try {
7868 if (null != newDefaultNetwork) {
7869 mNetd.networkSetDefault(newDefaultNetwork.network.getNetId());
7870 } else {
7871 mNetd.networkClearDefault();
7872 }
7873 } catch (RemoteException | ServiceSpecificException e) {
7874 loge("Exception setting default network :" + e);
7875 }
7876 }
7877
7878 private void processListenRequests(@NonNull final NetworkAgentInfo nai) {
7879 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
7880 processNewlyLostListenRequests(nai);
7881 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
7882 processNewlySatisfiedListenRequests(nai);
7883 }
7884
7885 private void processNewlyLostListenRequests(@NonNull final NetworkAgentInfo nai) {
7886 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
7887 if (nri.isMultilayerRequest()) {
7888 continue;
7889 }
7890 final NetworkRequest nr = nri.mRequests.get(0);
7891 if (!nr.isListen()) continue;
7892 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
7893 nai.removeRequest(nr.requestId);
7894 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
7895 }
7896 }
7897 }
7898
7899 private void processNewlySatisfiedListenRequests(@NonNull final NetworkAgentInfo nai) {
7900 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
7901 if (nri.isMultilayerRequest()) {
7902 continue;
7903 }
7904 final NetworkRequest nr = nri.mRequests.get(0);
7905 if (!nr.isListen()) continue;
7906 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
7907 nai.addRequest(nr);
7908 notifyNetworkAvailable(nai, nri);
7909 }
7910 }
7911 }
7912
7913 // An accumulator class to gather the list of changes that result from a rematch.
7914 private static class NetworkReassignment {
7915 static class RequestReassignment {
7916 @NonNull public final NetworkRequestInfo mNetworkRequestInfo;
7917 @Nullable public final NetworkRequest mOldNetworkRequest;
7918 @Nullable public final NetworkRequest mNewNetworkRequest;
7919 @Nullable public final NetworkAgentInfo mOldNetwork;
7920 @Nullable public final NetworkAgentInfo mNewNetwork;
7921 RequestReassignment(@NonNull final NetworkRequestInfo networkRequestInfo,
7922 @Nullable final NetworkRequest oldNetworkRequest,
7923 @Nullable final NetworkRequest newNetworkRequest,
7924 @Nullable final NetworkAgentInfo oldNetwork,
7925 @Nullable final NetworkAgentInfo newNetwork) {
7926 mNetworkRequestInfo = networkRequestInfo;
7927 mOldNetworkRequest = oldNetworkRequest;
7928 mNewNetworkRequest = newNetworkRequest;
7929 mOldNetwork = oldNetwork;
7930 mNewNetwork = newNetwork;
7931 }
7932
7933 public String toString() {
7934 final NetworkRequest requestToShow = null != mNewNetworkRequest
7935 ? mNewNetworkRequest : mNetworkRequestInfo.mRequests.get(0);
7936 return requestToShow.requestId + " : "
7937 + (null != mOldNetwork ? mOldNetwork.network.getNetId() : "null")
7938 + " → " + (null != mNewNetwork ? mNewNetwork.network.getNetId() : "null");
7939 }
7940 }
7941
7942 @NonNull private final ArrayList<RequestReassignment> mReassignments = new ArrayList<>();
7943
7944 @NonNull Iterable<RequestReassignment> getRequestReassignments() {
7945 return mReassignments;
7946 }
7947
7948 void addRequestReassignment(@NonNull final RequestReassignment reassignment) {
7949 if (Build.isDebuggable()) {
7950 // The code is never supposed to add two reassignments of the same request. Make
7951 // sure this stays true, but without imposing this expensive check on all
7952 // reassignments on all user devices.
7953 for (final RequestReassignment existing : mReassignments) {
7954 if (existing.mNetworkRequestInfo.equals(reassignment.mNetworkRequestInfo)) {
7955 throw new IllegalStateException("Trying to reassign ["
7956 + reassignment + "] but already have ["
7957 + existing + "]");
7958 }
7959 }
7960 }
7961 mReassignments.add(reassignment);
7962 }
7963
7964 // Will return null if this reassignment does not change the network assigned to
7965 // the passed request.
7966 @Nullable
7967 private RequestReassignment getReassignment(@NonNull final NetworkRequestInfo nri) {
7968 for (final RequestReassignment event : getRequestReassignments()) {
7969 if (nri == event.mNetworkRequestInfo) return event;
7970 }
7971 return null;
7972 }
7973
7974 public String toString() {
7975 final StringJoiner sj = new StringJoiner(", " /* delimiter */,
7976 "NetReassign [" /* prefix */, "]" /* suffix */);
7977 if (mReassignments.isEmpty()) return sj.add("no changes").toString();
7978 for (final RequestReassignment rr : getRequestReassignments()) {
7979 sj.add(rr.toString());
7980 }
7981 return sj.toString();
7982 }
7983
7984 public String debugString() {
7985 final StringBuilder sb = new StringBuilder();
7986 sb.append("NetworkReassignment :");
7987 if (mReassignments.isEmpty()) return sb.append(" no changes").toString();
7988 for (final RequestReassignment rr : getRequestReassignments()) {
7989 sb.append("\n ").append(rr);
7990 }
7991 return sb.append("\n").toString();
7992 }
7993 }
7994
7995 private void updateSatisfiersForRematchRequest(@NonNull final NetworkRequestInfo nri,
7996 @Nullable final NetworkRequest previousRequest,
7997 @Nullable final NetworkRequest newRequest,
7998 @Nullable final NetworkAgentInfo previousSatisfier,
7999 @Nullable final NetworkAgentInfo newSatisfier,
8000 final long now) {
8001 if (null != newSatisfier && mNoServiceNetwork != newSatisfier) {
8002 if (VDBG) log("rematch for " + newSatisfier.toShortString());
8003 if (null != previousRequest && null != previousSatisfier) {
8004 if (VDBG || DDBG) {
8005 log(" accepting network in place of " + previousSatisfier.toShortString());
8006 }
8007 previousSatisfier.removeRequest(previousRequest.requestId);
8008 previousSatisfier.lingerRequest(previousRequest.requestId, now);
8009 } else {
8010 if (VDBG || DDBG) log(" accepting network in place of null");
8011 }
8012
8013 // To prevent constantly CPU wake up for nascent timer, if a network comes up
8014 // and immediately satisfies a request then remove the timer. This will happen for
8015 // all networks except in the case of an underlying network for a VCN.
8016 if (newSatisfier.isNascent()) {
8017 newSatisfier.unlingerRequest(NetworkRequest.REQUEST_ID_NONE);
8018 newSatisfier.unsetInactive();
8019 }
8020
8021 // if newSatisfier is not null, then newRequest may not be null.
8022 newSatisfier.unlingerRequest(newRequest.requestId);
8023 if (!newSatisfier.addRequest(newRequest)) {
8024 Log.wtf(TAG, "BUG: " + newSatisfier.toShortString() + " already has "
8025 + newRequest);
8026 }
8027 } else if (null != previousRequest && null != previousSatisfier) {
8028 if (DBG) {
8029 log("Network " + previousSatisfier.toShortString() + " stopped satisfying"
8030 + " request " + previousRequest.requestId);
8031 }
8032 previousSatisfier.removeRequest(previousRequest.requestId);
8033 }
8034 nri.setSatisfier(newSatisfier, newRequest);
8035 }
8036
8037 /**
8038 * This function is triggered when something can affect what network should satisfy what
8039 * request, and it computes the network reassignment from the passed collection of requests to
8040 * network match to the one that the system should now have. That data is encoded in an
8041 * object that is a list of changes, each of them having an NRI, and old satisfier, and a new
8042 * satisfier.
8043 *
8044 * After the reassignment is computed, it is applied to the state objects.
8045 *
8046 * @param networkRequests the nri objects to evaluate for possible network reassignment
8047 * @return NetworkReassignment listing of proposed network assignment changes
8048 */
8049 @NonNull
8050 private NetworkReassignment computeNetworkReassignment(
8051 @NonNull final Collection<NetworkRequestInfo> networkRequests) {
8052 final NetworkReassignment changes = new NetworkReassignment();
8053
8054 // Gather the list of all relevant agents.
8055 final ArrayList<NetworkAgentInfo> nais = new ArrayList<>();
8056 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
8057 if (!nai.everConnected) {
8058 continue;
8059 }
8060 nais.add(nai);
8061 }
8062
8063 for (final NetworkRequestInfo nri : networkRequests) {
8064 // Non-multilayer listen requests can be ignored.
8065 if (!nri.isMultilayerRequest() && nri.mRequests.get(0).isListen()) {
8066 continue;
8067 }
8068 NetworkAgentInfo bestNetwork = null;
8069 NetworkRequest bestRequest = null;
8070 for (final NetworkRequest req : nri.mRequests) {
8071 bestNetwork = mNetworkRanker.getBestNetwork(req, nais, nri.getSatisfier());
8072 // Stop evaluating as the highest possible priority request is satisfied.
8073 if (null != bestNetwork) {
8074 bestRequest = req;
8075 break;
8076 }
8077 }
8078 if (null == bestNetwork && isDefaultBlocked(nri)) {
8079 // Remove default networking if disallowed for managed default requests.
8080 bestNetwork = mNoServiceNetwork;
8081 }
8082 if (nri.getSatisfier() != bestNetwork) {
8083 // bestNetwork may be null if no network can satisfy this request.
8084 changes.addRequestReassignment(new NetworkReassignment.RequestReassignment(
8085 nri, nri.mActiveRequest, bestRequest, nri.getSatisfier(), bestNetwork));
8086 }
8087 }
8088 return changes;
8089 }
8090
8091 private Set<NetworkRequestInfo> getNrisFromGlobalRequests() {
8092 return new HashSet<>(mNetworkRequests.values());
8093 }
8094
8095 /**
8096 * Attempt to rematch all Networks with all NetworkRequests. This may result in Networks
8097 * being disconnected.
8098 */
8099 private void rematchAllNetworksAndRequests() {
8100 rematchNetworksAndRequests(getNrisFromGlobalRequests());
8101 }
8102
8103 /**
8104 * Attempt to rematch all Networks with given NetworkRequests. This may result in Networks
8105 * being disconnected.
8106 */
8107 private void rematchNetworksAndRequests(
8108 @NonNull final Set<NetworkRequestInfo> networkRequests) {
8109 ensureRunningOnConnectivityServiceThread();
8110 // TODO: This may be slow, and should be optimized.
8111 final long now = SystemClock.elapsedRealtime();
8112 final NetworkReassignment changes = computeNetworkReassignment(networkRequests);
8113 if (VDBG || DDBG) {
8114 log(changes.debugString());
8115 } else if (DBG) {
8116 log(changes.toString()); // Shorter form, only one line of log
8117 }
8118 applyNetworkReassignment(changes, now);
8119 issueNetworkNeeds();
8120 }
8121
8122 private void applyNetworkReassignment(@NonNull final NetworkReassignment changes,
8123 final long now) {
8124 final Collection<NetworkAgentInfo> nais = mNetworkAgentInfos;
8125
8126 // Since most of the time there are only 0 or 1 background networks, it would probably
8127 // be more efficient to just use an ArrayList here. TODO : measure performance
8128 final ArraySet<NetworkAgentInfo> oldBgNetworks = new ArraySet<>();
8129 for (final NetworkAgentInfo nai : nais) {
8130 if (nai.isBackgroundNetwork()) oldBgNetworks.add(nai);
8131 }
8132
8133 // First, update the lists of satisfied requests in the network agents. This is necessary
8134 // because some code later depends on this state to be correct, most prominently computing
8135 // the linger status.
8136 for (final NetworkReassignment.RequestReassignment event :
8137 changes.getRequestReassignments()) {
8138 updateSatisfiersForRematchRequest(event.mNetworkRequestInfo,
8139 event.mOldNetworkRequest, event.mNewNetworkRequest,
8140 event.mOldNetwork, event.mNewNetwork,
8141 now);
8142 }
8143
8144 // Process default network changes if applicable.
8145 processDefaultNetworkChanges(changes);
8146
8147 // Notify requested networks are available after the default net is switched, but
8148 // before LegacyTypeTracker sends legacy broadcasts
8149 for (final NetworkReassignment.RequestReassignment event :
8150 changes.getRequestReassignments()) {
8151 if (null != event.mNewNetwork) {
8152 notifyNetworkAvailable(event.mNewNetwork, event.mNetworkRequestInfo);
8153 } else {
8154 callCallbackForRequest(event.mNetworkRequestInfo, event.mOldNetwork,
8155 ConnectivityManager.CALLBACK_LOST, 0);
8156 }
8157 }
8158
8159 // Update the inactivity state before processing listen callbacks, because the background
8160 // computation depends on whether the network is inactive. Don't send the LOSING callbacks
8161 // just yet though, because they have to be sent after the listens are processed to keep
8162 // backward compatibility.
8163 final ArrayList<NetworkAgentInfo> inactiveNetworks = new ArrayList<>();
8164 for (final NetworkAgentInfo nai : nais) {
8165 // Rematching may have altered the inactivity state of some networks, so update all
8166 // inactivity timers. updateInactivityState reads the state from the network agent
8167 // and does nothing if the state has not changed : the source of truth is controlled
8168 // with NetworkAgentInfo#lingerRequest and NetworkAgentInfo#unlingerRequest, which
8169 // have been called while rematching the individual networks above.
8170 if (updateInactivityState(nai, now)) {
8171 inactiveNetworks.add(nai);
8172 }
8173 }
8174
8175 for (final NetworkAgentInfo nai : nais) {
8176 if (!nai.everConnected) continue;
8177 final boolean oldBackground = oldBgNetworks.contains(nai);
8178 // Process listen requests and update capabilities if the background state has
8179 // changed for this network. For consistency with previous behavior, send onLost
8180 // callbacks before onAvailable.
8181 processNewlyLostListenRequests(nai);
8182 if (oldBackground != nai.isBackgroundNetwork()) {
8183 applyBackgroundChangeForRematch(nai);
8184 }
8185 processNewlySatisfiedListenRequests(nai);
8186 }
8187
8188 for (final NetworkAgentInfo nai : inactiveNetworks) {
8189 // For nascent networks, if connecting with no foreground request, skip broadcasting
8190 // LOSING for backward compatibility. This is typical when mobile data connected while
8191 // wifi connected with mobile data always-on enabled.
8192 if (nai.isNascent()) continue;
8193 notifyNetworkLosing(nai, now);
8194 }
8195
8196 updateLegacyTypeTrackerAndVpnLockdownForRematch(changes, nais);
8197
8198 // Tear down all unneeded networks.
8199 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
8200 if (unneeded(nai, UnneededFor.TEARDOWN)) {
8201 if (nai.getInactivityExpiry() > 0) {
8202 // This network has active linger timers and no requests, but is not
8203 // lingering. Linger it.
8204 //
8205 // One way (the only way?) this can happen if this network is unvalidated
8206 // and became unneeded due to another network improving its score to the
8207 // point where this network will no longer be able to satisfy any requests
8208 // even if it validates.
8209 if (updateInactivityState(nai, now)) {
8210 notifyNetworkLosing(nai, now);
8211 }
8212 } else {
8213 if (DBG) log("Reaping " + nai.toShortString());
8214 teardownUnneededNetwork(nai);
8215 }
8216 }
8217 }
8218 }
8219
8220 /**
8221 * Apply a change in background state resulting from rematching networks with requests.
8222 *
8223 * During rematch, a network may change background states by starting to satisfy or stopping
8224 * to satisfy a foreground request. Listens don't count for this. When a network changes
8225 * background states, its capabilities need to be updated and callbacks fired for the
8226 * capability change.
8227 *
8228 * @param nai The network that changed background states
8229 */
8230 private void applyBackgroundChangeForRematch(@NonNull final NetworkAgentInfo nai) {
8231 final NetworkCapabilities newNc = mixInCapabilities(nai, nai.networkCapabilities);
8232 if (Objects.equals(nai.networkCapabilities, newNc)) return;
8233 updateNetworkPermissions(nai, newNc);
8234 nai.getAndSetNetworkCapabilities(newNc);
8235 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
8236 }
8237
8238 private void updateLegacyTypeTrackerAndVpnLockdownForRematch(
8239 @NonNull final NetworkReassignment changes,
8240 @NonNull final Collection<NetworkAgentInfo> nais) {
8241 final NetworkReassignment.RequestReassignment reassignmentOfDefault =
8242 changes.getReassignment(mDefaultRequest);
8243 final NetworkAgentInfo oldDefaultNetwork =
8244 null != reassignmentOfDefault ? reassignmentOfDefault.mOldNetwork : null;
8245 final NetworkAgentInfo newDefaultNetwork =
8246 null != reassignmentOfDefault ? reassignmentOfDefault.mNewNetwork : null;
8247
8248 if (oldDefaultNetwork != newDefaultNetwork) {
8249 // Maintain the illusion : since the legacy API only understands one network at a time,
8250 // if the default network changed, apps should see a disconnected broadcast for the
8251 // old default network before they see a connected broadcast for the new one.
8252 if (oldDefaultNetwork != null) {
8253 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
8254 oldDefaultNetwork, true);
8255 }
8256 if (newDefaultNetwork != null) {
8257 // The new default network can be newly null if and only if the old default
8258 // network doesn't satisfy the default request any more because it lost a
8259 // capability.
8260 mDefaultInetConditionPublished = newDefaultNetwork.lastValidated ? 100 : 0;
8261 mLegacyTypeTracker.add(
8262 newDefaultNetwork.networkInfo.getType(), newDefaultNetwork);
8263 }
8264 }
8265
8266 // Now that all the callbacks have been sent, send the legacy network broadcasts
8267 // as needed. This is necessary so that legacy requests correctly bind dns
8268 // requests to this network. The legacy users are listening for this broadcast
8269 // and will generally do a dns request so they can ensureRouteToHost and if
8270 // they do that before the callbacks happen they'll use the default network.
8271 //
8272 // TODO: Is there still a race here? The legacy broadcast will be sent after sending
8273 // callbacks, but if apps can receive the broadcast before the callback, they still might
8274 // have an inconsistent view of networking.
8275 //
8276 // This *does* introduce a race where if the user uses the new api
8277 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
8278 // they may get old info. Reverse this after the old startUsing api is removed.
8279 // This is on top of the multiple intent sequencing referenced in the todo above.
8280 for (NetworkAgentInfo nai : nais) {
8281 if (nai.everConnected) {
8282 addNetworkToLegacyTypeTracker(nai);
8283 }
8284 }
8285 }
8286
8287 private void issueNetworkNeeds() {
8288 ensureRunningOnConnectivityServiceThread();
8289 for (final NetworkOfferInfo noi : mNetworkOffers) {
8290 issueNetworkNeeds(noi);
8291 }
8292 }
8293
8294 private void issueNetworkNeeds(@NonNull final NetworkOfferInfo noi) {
8295 ensureRunningOnConnectivityServiceThread();
8296 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
8297 informOffer(nri, noi.offer, mNetworkRanker);
8298 }
8299 }
8300
8301 /**
8302 * Inform a NetworkOffer about any new situation of a request.
8303 *
8304 * This function handles updates to offers. A number of events may happen that require
8305 * updating the registrant for this offer about the situation :
8306 * • The offer itself was updated. This may lead the offer to no longer being able
8307 * to satisfy a request or beat a satisfier (and therefore be no longer needed),
8308 * or conversely being strengthened enough to beat the satisfier (and therefore
8309 * start being needed)
8310 * • The network satisfying a request changed (including cases where the request
8311 * starts or stops being satisfied). The new network may be a stronger or weaker
8312 * match than the old one, possibly affecting whether the offer is needed.
8313 * • The network satisfying a request updated their score. This may lead the offer
8314 * to no longer be able to beat it if the current satisfier got better, or
8315 * conversely start being a good choice if the current satisfier got weaker.
8316 *
8317 * @param nri The request
8318 * @param offer The offer. This may be an updated offer.
8319 */
8320 private static void informOffer(@NonNull NetworkRequestInfo nri,
8321 @NonNull final NetworkOffer offer, @NonNull final NetworkRanker networkRanker) {
8322 final NetworkRequest activeRequest = nri.isBeingSatisfied() ? nri.getActiveRequest() : null;
8323 final NetworkAgentInfo satisfier = null != activeRequest ? nri.getSatisfier() : null;
8324
8325 // Multi-layer requests have a currently active request, the one being satisfied.
8326 // Since the system will try to bring up a better network than is currently satisfying
8327 // the request, NetworkProviders need to be told the offers matching the requests *above*
8328 // the currently satisfied one are needed, that the ones *below* the satisfied one are
8329 // not needed, and the offer is needed for the active request iff the offer can beat
8330 // the satisfier.
8331 // For non-multilayer requests, the logic above gracefully degenerates to only the
8332 // last case.
8333 // To achieve this, the loop below will proceed in three steps. In a first phase, inform
8334 // providers that the offer is needed for this request, until the active request is found.
8335 // In a second phase, deal with the currently active request. In a third phase, inform
8336 // the providers that offer is unneeded for the remaining requests.
8337
8338 // First phase : inform providers of all requests above the active request.
8339 int i;
8340 for (i = 0; nri.mRequests.size() > i; ++i) {
8341 final NetworkRequest request = nri.mRequests.get(i);
8342 if (activeRequest == request) break; // Found the active request : go to phase 2
8343 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
8344 // Since this request is higher-priority than the one currently satisfied, if the
8345 // offer can satisfy it, the provider should try and bring up the network for sure ;
8346 // no need to even ask the ranker – an offer that can satisfy is always better than
8347 // no network. Hence tell the provider so unless it already knew.
8348 if (request.canBeSatisfiedBy(offer.caps) && !offer.neededFor(request)) {
8349 offer.onNetworkNeeded(request);
8350 }
8351 }
8352
8353 // Second phase : deal with the active request (if any)
8354 if (null != activeRequest && activeRequest.isRequest()) {
8355 final boolean oldNeeded = offer.neededFor(activeRequest);
Junyu Lai135f5062021-07-05 09:09:01 +00008356 // If an offer can satisfy the request, it is considered needed if it is currently
8357 // served by this provider or if this offer can beat the current satisfier.
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00008358 final boolean currentlyServing = satisfier != null
Junyu Lai135f5062021-07-05 09:09:01 +00008359 && satisfier.factorySerialNumber == offer.providerId
8360 && activeRequest.canBeSatisfiedBy(offer.caps);
8361 final boolean newNeeded = currentlyServing
8362 || networkRanker.mightBeat(activeRequest, satisfier, offer);
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00008363 if (newNeeded != oldNeeded) {
8364 if (newNeeded) {
8365 offer.onNetworkNeeded(activeRequest);
8366 } else {
8367 // The offer used to be able to beat the satisfier. Now it can't.
8368 offer.onNetworkUnneeded(activeRequest);
8369 }
8370 }
8371 }
8372
8373 // Third phase : inform the providers that the offer isn't needed for any request
8374 // below the active one.
8375 for (++i /* skip the active request */; nri.mRequests.size() > i; ++i) {
8376 final NetworkRequest request = nri.mRequests.get(i);
8377 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
8378 // Since this request is lower-priority than the one currently satisfied, if the
8379 // offer can satisfy it, the provider should not try and bring up the network.
8380 // Hence tell the provider so unless it already knew.
8381 if (offer.neededFor(request)) {
8382 offer.onNetworkUnneeded(request);
8383 }
8384 }
8385 }
8386
8387 private void addNetworkToLegacyTypeTracker(@NonNull final NetworkAgentInfo nai) {
8388 for (int i = 0; i < nai.numNetworkRequests(); i++) {
8389 NetworkRequest nr = nai.requestAt(i);
8390 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
8391 // legacy type tracker filters out repeat adds
8392 mLegacyTypeTracker.add(nr.legacyType, nai);
8393 }
8394 }
8395
8396 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
8397 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
8398 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
8399 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
8400 if (nai.isVPN()) {
8401 mLegacyTypeTracker.add(TYPE_VPN, nai);
8402 }
8403 }
8404
8405 private void updateInetCondition(NetworkAgentInfo nai) {
8406 // Don't bother updating until we've graduated to validated at least once.
8407 if (!nai.everValidated) return;
8408 // For now only update icons for the default connection.
8409 // TODO: Update WiFi and cellular icons separately. b/17237507
8410 if (!isDefaultNetwork(nai)) return;
8411
8412 int newInetCondition = nai.lastValidated ? 100 : 0;
8413 // Don't repeat publish.
8414 if (newInetCondition == mDefaultInetConditionPublished) return;
8415
8416 mDefaultInetConditionPublished = newInetCondition;
8417 sendInetConditionBroadcast(nai.networkInfo);
8418 }
8419
8420 @NonNull
8421 private NetworkInfo mixInInfo(@NonNull final NetworkAgentInfo nai, @NonNull NetworkInfo info) {
8422 final NetworkInfo newInfo = new NetworkInfo(info);
8423 // The suspended and roaming bits are managed in NetworkCapabilities.
8424 final boolean suspended =
8425 !nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
8426 if (suspended && info.getDetailedState() == NetworkInfo.DetailedState.CONNECTED) {
8427 // Only override the state with SUSPENDED if the network is currently in CONNECTED
8428 // state. This is because the network could have been suspended before connecting,
8429 // or it could be disconnecting while being suspended, and in both these cases
8430 // the state should not be overridden. Note that the only detailed state that
8431 // maps to State.CONNECTED is DetailedState.CONNECTED, so there is also no need to
8432 // worry about multiple different substates of CONNECTED.
8433 newInfo.setDetailedState(NetworkInfo.DetailedState.SUSPENDED, info.getReason(),
8434 info.getExtraInfo());
8435 } else if (!suspended && info.getDetailedState() == NetworkInfo.DetailedState.SUSPENDED) {
8436 // SUSPENDED state is currently only overridden from CONNECTED state. In the case the
8437 // network agent is created, then goes to suspended, then goes out of suspended without
8438 // ever setting connected. Check if network agent is ever connected to update the state.
8439 newInfo.setDetailedState(nai.everConnected
8440 ? NetworkInfo.DetailedState.CONNECTED
8441 : NetworkInfo.DetailedState.CONNECTING,
8442 info.getReason(),
8443 info.getExtraInfo());
8444 }
8445 newInfo.setRoaming(!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_ROAMING));
8446 return newInfo;
8447 }
8448
8449 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo info) {
8450 final NetworkInfo newInfo = mixInInfo(networkAgent, info);
8451
8452 final NetworkInfo.State state = newInfo.getState();
8453 NetworkInfo oldInfo = null;
8454 synchronized (networkAgent) {
8455 oldInfo = networkAgent.networkInfo;
8456 networkAgent.networkInfo = newInfo;
8457 }
8458
8459 if (DBG) {
8460 log(networkAgent.toShortString() + " EVENT_NETWORK_INFO_CHANGED, going from "
8461 + oldInfo.getState() + " to " + state);
8462 }
8463
8464 if (!networkAgent.created
8465 && (state == NetworkInfo.State.CONNECTED
8466 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
8467
8468 // A network that has just connected has zero requests and is thus a foreground network.
8469 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
8470
8471 if (!createNativeNetwork(networkAgent)) return;
Treehugger Robot4703a8c2021-07-02 13:55:33 +00008472 if (networkAgent.propagateUnderlyingCapabilities()) {
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00008473 // Initialize the network's capabilities to their starting values according to the
8474 // underlying networks. This ensures that the capabilities are correct before
8475 // anything happens to the network.
8476 updateCapabilitiesForNetwork(networkAgent);
8477 }
8478 networkAgent.created = true;
8479 networkAgent.onNetworkCreated();
8480 }
8481
8482 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
8483 networkAgent.everConnected = true;
8484
8485 // NetworkCapabilities need to be set before sending the private DNS config to
8486 // NetworkMonitor, otherwise NetworkMonitor cannot determine if validation is required.
8487 networkAgent.getAndSetNetworkCapabilities(networkAgent.networkCapabilities);
8488
8489 handlePerNetworkPrivateDnsConfig(networkAgent, mDnsManager.getPrivateDnsConfig());
8490 updateLinkProperties(networkAgent, new LinkProperties(networkAgent.linkProperties),
8491 null);
8492
8493 // Until parceled LinkProperties are sent directly to NetworkMonitor, the connect
8494 // command must be sent after updating LinkProperties to maximize chances of
8495 // NetworkMonitor seeing the correct LinkProperties when starting.
8496 // TODO: pass LinkProperties to the NetworkMonitor in the notifyNetworkConnected call.
8497 if (networkAgent.networkAgentConfig.acceptPartialConnectivity) {
8498 networkAgent.networkMonitor().setAcceptPartialConnectivity();
8499 }
8500 networkAgent.networkMonitor().notifyNetworkConnected(
8501 new LinkProperties(networkAgent.linkProperties,
8502 true /* parcelSensitiveFields */),
8503 networkAgent.networkCapabilities);
8504 scheduleUnvalidatedPrompt(networkAgent);
8505
8506 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
8507 // be communicated to a particular NetworkAgent depends only on the network's immutable,
8508 // capabilities, so it only needs to be done once on initial connect, not every time the
8509 // network's capabilities change. Note that we do this before rematching the network,
8510 // so we could decide to tear it down immediately afterwards. That's fine though - on
8511 // disconnection NetworkAgents should stop any signal strength monitoring they have been
8512 // doing.
8513 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
8514
8515 // Before first rematching networks, put an inactivity timer without any request, this
8516 // allows {@code updateInactivityState} to update the state accordingly and prevent
8517 // tearing down for any {@code unneeded} evaluation in this period.
8518 // Note that the timer will not be rescheduled since the expiry time is
8519 // fixed after connection regardless of the network satisfying other requests or not.
8520 // But it will be removed as soon as the network satisfies a request for the first time.
8521 networkAgent.lingerRequest(NetworkRequest.REQUEST_ID_NONE,
8522 SystemClock.elapsedRealtime(), mNascentDelayMs);
8523 networkAgent.setInactive();
8524
8525 // Consider network even though it is not yet validated.
8526 rematchAllNetworksAndRequests();
8527
8528 // This has to happen after matching the requests, because callbacks are just requests.
8529 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
8530 } else if (state == NetworkInfo.State.DISCONNECTED) {
8531 networkAgent.disconnect();
8532 if (networkAgent.isVPN()) {
8533 updateUids(networkAgent, networkAgent.networkCapabilities, null);
8534 }
8535 disconnectAndDestroyNetwork(networkAgent);
8536 if (networkAgent.isVPN()) {
8537 // As the active or bound network changes for apps, broadcast the default proxy, as
8538 // apps may need to update their proxy data. This is called after disconnecting from
8539 // VPN to make sure we do not broadcast the old proxy data.
8540 // TODO(b/122649188): send the broadcast only to VPN users.
8541 mProxyTracker.sendProxyBroadcast();
8542 }
8543 } else if (networkAgent.created && (oldInfo.getState() == NetworkInfo.State.SUSPENDED ||
8544 state == NetworkInfo.State.SUSPENDED)) {
8545 mLegacyTypeTracker.update(networkAgent);
8546 }
8547 }
8548
8549 private void updateNetworkScore(@NonNull final NetworkAgentInfo nai, final NetworkScore score) {
8550 if (VDBG || DDBG) log("updateNetworkScore for " + nai.toShortString() + " to " + score);
8551 nai.setScore(score);
8552 rematchAllNetworksAndRequests();
8553 }
8554
8555 // Notify only this one new request of the current state. Transfer all the
8556 // current state by calling NetworkCapabilities and LinkProperties callbacks
8557 // so that callers can be guaranteed to have as close to atomicity in state
8558 // transfer as can be supported by this current API.
8559 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
8560 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
8561 if (nri.mPendingIntent != null) {
8562 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
8563 // Attempt no subsequent state pushes where intents are involved.
8564 return;
8565 }
8566
8567 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
8568 final boolean metered = nai.networkCapabilities.isMetered();
8569 final boolean vpnBlocked = isUidBlockedByVpn(nri.mAsUid, mVpnBlockedUidRanges);
8570 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE,
8571 getBlockedState(blockedReasons, metered, vpnBlocked));
8572 }
8573
8574 // Notify the requests on this NAI that the network is now lingered.
8575 private void notifyNetworkLosing(@NonNull final NetworkAgentInfo nai, final long now) {
8576 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
8577 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
8578 }
8579
8580 private static int getBlockedState(int reasons, boolean metered, boolean vpnBlocked) {
8581 if (!metered) reasons &= ~BLOCKED_METERED_REASON_MASK;
8582 return vpnBlocked
8583 ? reasons | BLOCKED_REASON_LOCKDOWN_VPN
8584 : reasons & ~BLOCKED_REASON_LOCKDOWN_VPN;
8585 }
8586
8587 private void setUidBlockedReasons(int uid, @BlockedReason int blockedReasons) {
8588 if (blockedReasons == BLOCKED_REASON_NONE) {
8589 mUidBlockedReasons.delete(uid);
8590 } else {
8591 mUidBlockedReasons.put(uid, blockedReasons);
8592 }
8593 }
8594
8595 /**
8596 * Notify of the blocked state apps with a registered callback matching a given NAI.
8597 *
8598 * Unlike other callbacks, blocked status is different between each individual uid. So for
8599 * any given nai, all requests need to be considered according to the uid who filed it.
8600 *
8601 * @param nai The target NetworkAgentInfo.
8602 * @param oldMetered True if the previous network capabilities were metered.
8603 * @param newMetered True if the current network capabilities are metered.
8604 * @param oldBlockedUidRanges list of UID ranges previously blocked by lockdown VPN.
8605 * @param newBlockedUidRanges list of UID ranges blocked by lockdown VPN.
8606 */
8607 private void maybeNotifyNetworkBlocked(NetworkAgentInfo nai, boolean oldMetered,
8608 boolean newMetered, List<UidRange> oldBlockedUidRanges,
8609 List<UidRange> newBlockedUidRanges) {
8610
8611 for (int i = 0; i < nai.numNetworkRequests(); i++) {
8612 NetworkRequest nr = nai.requestAt(i);
8613 NetworkRequestInfo nri = mNetworkRequests.get(nr);
8614
8615 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
8616 final boolean oldVpnBlocked = isUidBlockedByVpn(nri.mAsUid, oldBlockedUidRanges);
8617 final boolean newVpnBlocked = (oldBlockedUidRanges != newBlockedUidRanges)
8618 ? isUidBlockedByVpn(nri.mAsUid, newBlockedUidRanges)
8619 : oldVpnBlocked;
8620
8621 final int oldBlockedState = getBlockedState(blockedReasons, oldMetered, oldVpnBlocked);
8622 final int newBlockedState = getBlockedState(blockedReasons, newMetered, newVpnBlocked);
8623 if (oldBlockedState != newBlockedState) {
8624 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
8625 newBlockedState);
8626 }
8627 }
8628 }
8629
8630 /**
8631 * Notify apps with a given UID of the new blocked state according to new uid state.
8632 * @param uid The uid for which the rules changed.
8633 * @param blockedReasons The reasons for why an uid is blocked.
8634 */
8635 private void maybeNotifyNetworkBlockedForNewState(int uid, @BlockedReason int blockedReasons) {
8636 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
8637 final boolean metered = nai.networkCapabilities.isMetered();
8638 final boolean vpnBlocked = isUidBlockedByVpn(uid, mVpnBlockedUidRanges);
8639
8640 final int oldBlockedState = getBlockedState(
8641 mUidBlockedReasons.get(uid, BLOCKED_REASON_NONE), metered, vpnBlocked);
8642 final int newBlockedState = getBlockedState(blockedReasons, metered, vpnBlocked);
8643 if (oldBlockedState == newBlockedState) {
8644 continue;
8645 }
8646 for (int i = 0; i < nai.numNetworkRequests(); i++) {
8647 NetworkRequest nr = nai.requestAt(i);
8648 NetworkRequestInfo nri = mNetworkRequests.get(nr);
8649 if (nri != null && nri.mAsUid == uid) {
8650 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
8651 newBlockedState);
8652 }
8653 }
8654 }
8655 }
8656
8657 @VisibleForTesting
8658 protected void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
8659 // The NetworkInfo we actually send out has no bearing on the real
8660 // state of affairs. For example, if the default connection is mobile,
8661 // and a request for HIPRI has just gone away, we need to pretend that
8662 // HIPRI has just disconnected. So we need to set the type to HIPRI and
8663 // the state to DISCONNECTED, even though the network is of type MOBILE
8664 // and is still connected.
8665 NetworkInfo info = new NetworkInfo(nai.networkInfo);
8666 info.setType(type);
8667 filterForLegacyLockdown(info);
8668 if (state != DetailedState.DISCONNECTED) {
8669 info.setDetailedState(state, null, info.getExtraInfo());
8670 sendConnectedBroadcast(info);
8671 } else {
8672 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
8673 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
8674 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
8675 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
8676 if (info.isFailover()) {
8677 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
8678 nai.networkInfo.setFailover(false);
8679 }
8680 if (info.getReason() != null) {
8681 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
8682 }
8683 if (info.getExtraInfo() != null) {
8684 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
8685 }
8686 NetworkAgentInfo newDefaultAgent = null;
8687 if (nai.isSatisfyingRequest(mDefaultRequest.mRequests.get(0).requestId)) {
8688 newDefaultAgent = mDefaultRequest.getSatisfier();
8689 if (newDefaultAgent != null) {
8690 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
8691 newDefaultAgent.networkInfo);
8692 } else {
8693 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
8694 }
8695 }
8696 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
8697 mDefaultInetConditionPublished);
8698 sendStickyBroadcast(intent);
8699 if (newDefaultAgent != null) {
8700 sendConnectedBroadcast(newDefaultAgent.networkInfo);
8701 }
8702 }
8703 }
8704
8705 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
8706 if (VDBG || DDBG) {
8707 String notification = ConnectivityManager.getCallbackName(notifyType);
8708 log("notifyType " + notification + " for " + networkAgent.toShortString());
8709 }
8710 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
8711 NetworkRequest nr = networkAgent.requestAt(i);
8712 NetworkRequestInfo nri = mNetworkRequests.get(nr);
8713 if (VDBG) log(" sending notification for " + nr);
8714 if (nri.mPendingIntent == null) {
8715 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
8716 } else {
8717 sendPendingIntentForRequest(nri, networkAgent, notifyType);
8718 }
8719 }
8720 }
8721
8722 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
8723 notifyNetworkCallbacks(networkAgent, notifyType, 0);
8724 }
8725
8726 /**
8727 * Returns the list of all interfaces that could be used by network traffic that does not
8728 * explicitly specify a network. This includes the default network, but also all VPNs that are
8729 * currently connected.
8730 *
8731 * Must be called on the handler thread.
8732 */
8733 @NonNull
8734 private ArrayList<Network> getDefaultNetworks() {
8735 ensureRunningOnConnectivityServiceThread();
8736 final ArrayList<Network> defaultNetworks = new ArrayList<>();
8737 final Set<Integer> activeNetIds = new ArraySet<>();
8738 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
8739 if (nri.isBeingSatisfied()) {
8740 activeNetIds.add(nri.getSatisfier().network().netId);
8741 }
8742 }
8743 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
8744 if (nai.everConnected && (activeNetIds.contains(nai.network().netId) || nai.isVPN())) {
8745 defaultNetworks.add(nai.network);
8746 }
8747 }
8748 return defaultNetworks;
8749 }
8750
8751 /**
8752 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
8753 * active iface's tracked properties has changed.
8754 */
8755 private void notifyIfacesChangedForNetworkStats() {
8756 ensureRunningOnConnectivityServiceThread();
8757 String activeIface = null;
8758 LinkProperties activeLinkProperties = getActiveLinkProperties();
8759 if (activeLinkProperties != null) {
8760 activeIface = activeLinkProperties.getInterfaceName();
8761 }
8762
8763 final UnderlyingNetworkInfo[] underlyingNetworkInfos = getAllVpnInfo();
8764 try {
8765 final ArrayList<NetworkStateSnapshot> snapshots = new ArrayList<>();
junyulai0f570222021-03-05 14:46:25 +08008766 for (final NetworkStateSnapshot snapshot : getAllNetworkStateSnapshots()) {
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00008767 snapshots.add(snapshot);
8768 }
8769 mStatsManager.notifyNetworkStatus(getDefaultNetworks(),
8770 snapshots, activeIface, Arrays.asList(underlyingNetworkInfos));
8771 } catch (Exception ignored) {
8772 }
8773 }
8774
8775 @Override
8776 public String getCaptivePortalServerUrl() {
8777 enforceNetworkStackOrSettingsPermission();
8778 String settingUrl = mResources.get().getString(
8779 R.string.config_networkCaptivePortalServerUrl);
8780
8781 if (!TextUtils.isEmpty(settingUrl)) {
8782 return settingUrl;
8783 }
8784
8785 settingUrl = Settings.Global.getString(mContext.getContentResolver(),
8786 ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL);
8787 if (!TextUtils.isEmpty(settingUrl)) {
8788 return settingUrl;
8789 }
8790
8791 return DEFAULT_CAPTIVE_PORTAL_HTTP_URL;
8792 }
8793
8794 @Override
8795 public void startNattKeepalive(Network network, int intervalSeconds,
8796 ISocketKeepaliveCallback cb, String srcAddr, int srcPort, String dstAddr) {
8797 enforceKeepalivePermission();
8798 mKeepaliveTracker.startNattKeepalive(
8799 getNetworkAgentInfoForNetwork(network), null /* fd */,
8800 intervalSeconds, cb,
8801 srcAddr, srcPort, dstAddr, NattSocketKeepalive.NATT_PORT);
8802 }
8803
8804 @Override
8805 public void startNattKeepaliveWithFd(Network network, ParcelFileDescriptor pfd, int resourceId,
8806 int intervalSeconds, ISocketKeepaliveCallback cb, String srcAddr,
8807 String dstAddr) {
8808 try {
8809 final FileDescriptor fd = pfd.getFileDescriptor();
8810 mKeepaliveTracker.startNattKeepalive(
8811 getNetworkAgentInfoForNetwork(network), fd, resourceId,
8812 intervalSeconds, cb,
8813 srcAddr, dstAddr, NattSocketKeepalive.NATT_PORT);
8814 } finally {
8815 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
8816 // startNattKeepalive calls Os.dup(fd) before returning, so we can close immediately.
8817 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
8818 IoUtils.closeQuietly(pfd);
8819 }
8820 }
8821 }
8822
8823 @Override
8824 public void startTcpKeepalive(Network network, ParcelFileDescriptor pfd, int intervalSeconds,
8825 ISocketKeepaliveCallback cb) {
8826 try {
8827 enforceKeepalivePermission();
8828 final FileDescriptor fd = pfd.getFileDescriptor();
8829 mKeepaliveTracker.startTcpKeepalive(
8830 getNetworkAgentInfoForNetwork(network), fd, intervalSeconds, cb);
8831 } finally {
8832 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
8833 // startTcpKeepalive calls Os.dup(fd) before returning, so we can close immediately.
8834 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
8835 IoUtils.closeQuietly(pfd);
8836 }
8837 }
8838 }
8839
8840 @Override
8841 public void stopKeepalive(Network network, int slot) {
8842 mHandler.sendMessage(mHandler.obtainMessage(
8843 NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE, slot, SocketKeepalive.SUCCESS, network));
8844 }
8845
8846 @Override
8847 public void factoryReset() {
8848 enforceSettingsPermission();
8849
Treehugger Robotfac2a722021-05-21 02:42:59 +00008850 final int uid = mDeps.getCallingUid();
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00008851 final long token = Binder.clearCallingIdentity();
8852 try {
Treehugger Robotfac2a722021-05-21 02:42:59 +00008853 if (mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_NETWORK_RESET,
8854 UserHandle.getUserHandleForUid(uid))) {
8855 return;
8856 }
8857
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00008858 final IpMemoryStore ipMemoryStore = IpMemoryStore.getMemoryStore(mContext);
8859 ipMemoryStore.factoryReset();
Treehugger Robotfac2a722021-05-21 02:42:59 +00008860
8861 // Turn airplane mode off
8862 setAirplaneMode(false);
8863
8864 // restore private DNS settings to default mode (opportunistic)
8865 if (!mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_CONFIG_PRIVATE_DNS,
8866 UserHandle.getUserHandleForUid(uid))) {
8867 ConnectivitySettingsManager.setPrivateDnsMode(mContext,
8868 PRIVATE_DNS_MODE_OPPORTUNISTIC);
8869 }
8870
8871 Settings.Global.putString(mContext.getContentResolver(),
8872 ConnectivitySettingsManager.NETWORK_AVOID_BAD_WIFI, null);
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00008873 } finally {
8874 Binder.restoreCallingIdentity(token);
8875 }
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00008876 }
8877
8878 @Override
8879 public byte[] getNetworkWatchlistConfigHash() {
8880 NetworkWatchlistManager nwm = mContext.getSystemService(NetworkWatchlistManager.class);
8881 if (nwm == null) {
8882 loge("Unable to get NetworkWatchlistManager");
8883 return null;
8884 }
8885 // Redirect it to network watchlist service to access watchlist file and calculate hash.
8886 return nwm.getWatchlistConfigHash();
8887 }
8888
8889 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
8890 int[] transports = nai.networkCapabilities.getTransportTypes();
8891 mMetricsLog.log(nai.network.getNetId(), transports, new NetworkEvent(evtype));
8892 }
8893
8894 private static boolean toBool(int encodedBoolean) {
8895 return encodedBoolean != 0; // Only 0 means false.
8896 }
8897
8898 private static int encodeBool(boolean b) {
8899 return b ? 1 : 0;
8900 }
8901
8902 @Override
8903 public int handleShellCommand(@NonNull ParcelFileDescriptor in,
8904 @NonNull ParcelFileDescriptor out, @NonNull ParcelFileDescriptor err,
8905 @NonNull String[] args) {
8906 return new ShellCmd().exec(this, in.getFileDescriptor(), out.getFileDescriptor(),
8907 err.getFileDescriptor(), args);
8908 }
8909
8910 private class ShellCmd extends BasicShellCommandHandler {
8911 @Override
8912 public int onCommand(String cmd) {
8913 if (cmd == null) {
8914 return handleDefaultCommands(cmd);
8915 }
8916 final PrintWriter pw = getOutPrintWriter();
8917 try {
8918 switch (cmd) {
8919 case "airplane-mode":
8920 final String action = getNextArg();
8921 if ("enable".equals(action)) {
8922 setAirplaneMode(true);
8923 return 0;
8924 } else if ("disable".equals(action)) {
8925 setAirplaneMode(false);
8926 return 0;
8927 } else if (action == null) {
8928 final ContentResolver cr = mContext.getContentResolver();
8929 final int enabled = Settings.Global.getInt(cr,
8930 Settings.Global.AIRPLANE_MODE_ON);
8931 pw.println(enabled == 0 ? "disabled" : "enabled");
8932 return 0;
8933 } else {
8934 onHelp();
8935 return -1;
8936 }
8937 default:
8938 return handleDefaultCommands(cmd);
8939 }
8940 } catch (Exception e) {
8941 pw.println(e);
8942 }
8943 return -1;
8944 }
8945
8946 @Override
8947 public void onHelp() {
8948 PrintWriter pw = getOutPrintWriter();
8949 pw.println("Connectivity service commands:");
8950 pw.println(" help");
8951 pw.println(" Print this help text.");
8952 pw.println(" airplane-mode [enable|disable]");
8953 pw.println(" Turn airplane mode on or off.");
8954 pw.println(" airplane-mode");
8955 pw.println(" Get airplane mode.");
8956 }
8957 }
8958
8959 private int getVpnType(@Nullable NetworkAgentInfo vpn) {
8960 if (vpn == null) return VpnManager.TYPE_VPN_NONE;
8961 final TransportInfo ti = vpn.networkCapabilities.getTransportInfo();
8962 if (!(ti instanceof VpnTransportInfo)) return VpnManager.TYPE_VPN_NONE;
8963 return ((VpnTransportInfo) ti).getType();
8964 }
8965
8966 /**
8967 * @param connectionInfo the connection to resolve.
8968 * @return {@code uid} if the connection is found and the app has permission to observe it
8969 * (e.g., if it is associated with the calling VPN app's tunnel) or {@code INVALID_UID} if the
8970 * connection is not found.
8971 */
8972 public int getConnectionOwnerUid(ConnectionInfo connectionInfo) {
8973 if (connectionInfo.protocol != IPPROTO_TCP && connectionInfo.protocol != IPPROTO_UDP) {
8974 throw new IllegalArgumentException("Unsupported protocol " + connectionInfo.protocol);
8975 }
8976
8977 final int uid = mDeps.getConnectionOwnerUid(connectionInfo.protocol,
8978 connectionInfo.local, connectionInfo.remote);
8979
8980 if (uid == INVALID_UID) return uid; // Not found.
8981
8982 // Connection owner UIDs are visible only to the network stack and to the VpnService-based
8983 // VPN, if any, that applies to the UID that owns the connection.
8984 if (checkNetworkStackPermission()) return uid;
8985
8986 final NetworkAgentInfo vpn = getVpnForUid(uid);
8987 if (vpn == null || getVpnType(vpn) != VpnManager.TYPE_VPN_SERVICE
8988 || vpn.networkCapabilities.getOwnerUid() != mDeps.getCallingUid()) {
8989 return INVALID_UID;
8990 }
8991
8992 return uid;
8993 }
8994
8995 /**
8996 * Returns a IBinder to a TestNetworkService. Will be lazily created as needed.
8997 *
8998 * <p>The TestNetworkService must be run in the system server due to TUN creation.
8999 */
9000 @Override
9001 public IBinder startOrGetTestNetworkService() {
9002 synchronized (mTNSLock) {
9003 TestNetworkService.enforceTestNetworkPermissions(mContext);
9004
9005 if (mTNS == null) {
9006 mTNS = new TestNetworkService(mContext);
9007 }
9008
9009 return mTNS;
9010 }
9011 }
9012
9013 /**
9014 * Handler used for managing all Connectivity Diagnostics related functions.
9015 *
9016 * @see android.net.ConnectivityDiagnosticsManager
9017 *
9018 * TODO(b/147816404): Explore moving ConnectivityDiagnosticsHandler to a separate file
9019 */
9020 @VisibleForTesting
9021 class ConnectivityDiagnosticsHandler extends Handler {
9022 private final String mTag = ConnectivityDiagnosticsHandler.class.getSimpleName();
9023
9024 /**
9025 * Used to handle ConnectivityDiagnosticsCallback registration events from {@link
9026 * android.net.ConnectivityDiagnosticsManager}.
9027 * obj = ConnectivityDiagnosticsCallbackInfo with IConnectivityDiagnosticsCallback and
9028 * NetworkRequestInfo to be registered
9029 */
9030 private static final int EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 1;
9031
9032 /**
9033 * Used to handle ConnectivityDiagnosticsCallback unregister events from {@link
9034 * android.net.ConnectivityDiagnosticsManager}.
9035 * obj = the IConnectivityDiagnosticsCallback to be unregistered
9036 * arg1 = the uid of the caller
9037 */
9038 private static final int EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 2;
9039
9040 /**
9041 * Event for {@link NetworkStateTrackerHandler} to trigger ConnectivityReport callbacks
9042 * after processing {@link #EVENT_NETWORK_TESTED} events.
9043 * obj = {@link ConnectivityReportEvent} representing ConnectivityReport info reported from
9044 * NetworkMonitor.
9045 * data = PersistableBundle of extras passed from NetworkMonitor.
9046 *
9047 * <p>See {@link ConnectivityService#EVENT_NETWORK_TESTED}.
9048 */
9049 private static final int EVENT_NETWORK_TESTED = ConnectivityService.EVENT_NETWORK_TESTED;
9050
9051 /**
9052 * Event for NetworkMonitor to inform ConnectivityService that a potential data stall has
9053 * been detected on the network.
9054 * obj = Long the timestamp (in millis) for when the suspected data stall was detected.
9055 * arg1 = {@link DataStallReport#DetectionMethod} indicating the detection method.
9056 * arg2 = NetID.
9057 * data = PersistableBundle of extras passed from NetworkMonitor.
9058 */
9059 private static final int EVENT_DATA_STALL_SUSPECTED = 4;
9060
9061 /**
9062 * Event for ConnectivityDiagnosticsHandler to handle network connectivity being reported to
9063 * the platform. This event will invoke {@link
9064 * IConnectivityDiagnosticsCallback#onNetworkConnectivityReported} for permissioned
9065 * callbacks.
9066 * obj = Network that was reported on
9067 * arg1 = boolint for the quality reported
9068 */
9069 private static final int EVENT_NETWORK_CONNECTIVITY_REPORTED = 5;
9070
9071 private ConnectivityDiagnosticsHandler(Looper looper) {
9072 super(looper);
9073 }
9074
9075 @Override
9076 public void handleMessage(Message msg) {
9077 switch (msg.what) {
9078 case EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
9079 handleRegisterConnectivityDiagnosticsCallback(
9080 (ConnectivityDiagnosticsCallbackInfo) msg.obj);
9081 break;
9082 }
9083 case EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
9084 handleUnregisterConnectivityDiagnosticsCallback(
9085 (IConnectivityDiagnosticsCallback) msg.obj, msg.arg1);
9086 break;
9087 }
9088 case EVENT_NETWORK_TESTED: {
9089 final ConnectivityReportEvent reportEvent =
9090 (ConnectivityReportEvent) msg.obj;
9091
9092 handleNetworkTestedWithExtras(reportEvent, reportEvent.mExtras);
9093 break;
9094 }
9095 case EVENT_DATA_STALL_SUSPECTED: {
9096 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
9097 final Pair<Long, PersistableBundle> arg =
9098 (Pair<Long, PersistableBundle>) msg.obj;
9099 if (nai == null) break;
9100
9101 handleDataStallSuspected(nai, arg.first, msg.arg1, arg.second);
9102 break;
9103 }
9104 case EVENT_NETWORK_CONNECTIVITY_REPORTED: {
9105 handleNetworkConnectivityReported((NetworkAgentInfo) msg.obj, toBool(msg.arg1));
9106 break;
9107 }
9108 default: {
9109 Log.e(mTag, "Unrecognized event in ConnectivityDiagnostics: " + msg.what);
9110 }
9111 }
9112 }
9113 }
9114
9115 /** Class used for cleaning up IConnectivityDiagnosticsCallback instances after their death. */
9116 @VisibleForTesting
9117 class ConnectivityDiagnosticsCallbackInfo implements Binder.DeathRecipient {
9118 @NonNull private final IConnectivityDiagnosticsCallback mCb;
9119 @NonNull private final NetworkRequestInfo mRequestInfo;
9120 @NonNull private final String mCallingPackageName;
9121
9122 @VisibleForTesting
9123 ConnectivityDiagnosticsCallbackInfo(
9124 @NonNull IConnectivityDiagnosticsCallback cb,
9125 @NonNull NetworkRequestInfo nri,
9126 @NonNull String callingPackageName) {
9127 mCb = cb;
9128 mRequestInfo = nri;
9129 mCallingPackageName = callingPackageName;
9130 }
9131
9132 @Override
9133 public void binderDied() {
9134 log("ConnectivityDiagnosticsCallback IBinder died.");
9135 unregisterConnectivityDiagnosticsCallback(mCb);
9136 }
9137 }
9138
9139 /**
9140 * Class used for sending information from {@link
9141 * NetworkMonitorCallbacks#notifyNetworkTestedWithExtras} to the handler for processing it.
9142 */
9143 private static class NetworkTestedResults {
9144 private final int mNetId;
9145 private final int mTestResult;
9146 private final long mTimestampMillis;
9147 @Nullable private final String mRedirectUrl;
9148
9149 private NetworkTestedResults(
9150 int netId, int testResult, long timestampMillis, @Nullable String redirectUrl) {
9151 mNetId = netId;
9152 mTestResult = testResult;
9153 mTimestampMillis = timestampMillis;
9154 mRedirectUrl = redirectUrl;
9155 }
9156 }
9157
9158 /**
9159 * Class used for sending information from {@link NetworkStateTrackerHandler} to {@link
9160 * ConnectivityDiagnosticsHandler}.
9161 */
9162 private static class ConnectivityReportEvent {
9163 private final long mTimestampMillis;
9164 @NonNull private final NetworkAgentInfo mNai;
9165 private final PersistableBundle mExtras;
9166
9167 private ConnectivityReportEvent(long timestampMillis, @NonNull NetworkAgentInfo nai,
9168 PersistableBundle p) {
9169 mTimestampMillis = timestampMillis;
9170 mNai = nai;
9171 mExtras = p;
9172 }
9173 }
9174
9175 private void handleRegisterConnectivityDiagnosticsCallback(
9176 @NonNull ConnectivityDiagnosticsCallbackInfo cbInfo) {
9177 ensureRunningOnConnectivityServiceThread();
9178
9179 final IConnectivityDiagnosticsCallback cb = cbInfo.mCb;
9180 final IBinder iCb = cb.asBinder();
9181 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
9182
9183 // Connectivity Diagnostics are meant to be used with a single network request. It would be
9184 // confusing for these networks to change when an NRI is satisfied in another layer.
9185 if (nri.isMultilayerRequest()) {
9186 throw new IllegalArgumentException("Connectivity Diagnostics do not support multilayer "
9187 + "network requests.");
9188 }
9189
9190 // This means that the client registered the same callback multiple times. Do
9191 // not override the previous entry, and exit silently.
9192 if (mConnectivityDiagnosticsCallbacks.containsKey(iCb)) {
9193 if (VDBG) log("Diagnostics callback is already registered");
9194
9195 // Decrement the reference count for this NetworkRequestInfo. The reference count is
9196 // incremented when the NetworkRequestInfo is created as part of
9197 // enforceRequestCountLimit().
9198 nri.decrementRequestCount();
9199 return;
9200 }
9201
9202 mConnectivityDiagnosticsCallbacks.put(iCb, cbInfo);
9203
9204 try {
9205 iCb.linkToDeath(cbInfo, 0);
9206 } catch (RemoteException e) {
9207 cbInfo.binderDied();
9208 return;
9209 }
9210
9211 // Once registered, provide ConnectivityReports for matching Networks
9212 final List<NetworkAgentInfo> matchingNetworks = new ArrayList<>();
9213 synchronized (mNetworkForNetId) {
9214 for (int i = 0; i < mNetworkForNetId.size(); i++) {
9215 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
9216 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0)
9217 if (nai.satisfies(nri.mRequests.get(0))) {
9218 matchingNetworks.add(nai);
9219 }
9220 }
9221 }
9222 for (final NetworkAgentInfo nai : matchingNetworks) {
9223 final ConnectivityReport report = nai.getConnectivityReport();
9224 if (report == null) {
9225 continue;
9226 }
9227 if (!checkConnectivityDiagnosticsPermissions(
9228 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
9229 continue;
9230 }
9231
9232 try {
9233 cb.onConnectivityReportAvailable(report);
9234 } catch (RemoteException e) {
9235 // Exception while sending the ConnectivityReport. Move on to the next network.
9236 }
9237 }
9238 }
9239
9240 private void handleUnregisterConnectivityDiagnosticsCallback(
9241 @NonNull IConnectivityDiagnosticsCallback cb, int uid) {
9242 ensureRunningOnConnectivityServiceThread();
9243 final IBinder iCb = cb.asBinder();
9244
9245 final ConnectivityDiagnosticsCallbackInfo cbInfo =
9246 mConnectivityDiagnosticsCallbacks.remove(iCb);
9247 if (cbInfo == null) {
9248 if (VDBG) log("Removing diagnostics callback that is not currently registered");
9249 return;
9250 }
9251
9252 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
9253
9254 // Caller's UID must either be the registrants (if they are unregistering) or the System's
9255 // (if the Binder died)
9256 if (uid != nri.mUid && uid != Process.SYSTEM_UID) {
9257 if (DBG) loge("Uid(" + uid + ") not registrant's (" + nri.mUid + ") or System's");
9258 return;
9259 }
9260
9261 // Decrement the reference count for this NetworkRequestInfo. The reference count is
9262 // incremented when the NetworkRequestInfo is created as part of
9263 // enforceRequestCountLimit().
9264 nri.decrementRequestCount();
9265
9266 iCb.unlinkToDeath(cbInfo, 0);
9267 }
9268
9269 private void handleNetworkTestedWithExtras(
9270 @NonNull ConnectivityReportEvent reportEvent, @NonNull PersistableBundle extras) {
9271 final NetworkAgentInfo nai = reportEvent.mNai;
9272 final NetworkCapabilities networkCapabilities =
9273 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
9274 final ConnectivityReport report =
9275 new ConnectivityReport(
9276 reportEvent.mNai.network,
9277 reportEvent.mTimestampMillis,
9278 nai.linkProperties,
9279 networkCapabilities,
9280 extras);
9281 nai.setConnectivityReport(report);
9282 final List<IConnectivityDiagnosticsCallback> results =
9283 getMatchingPermissionedCallbacks(nai);
9284 for (final IConnectivityDiagnosticsCallback cb : results) {
9285 try {
9286 cb.onConnectivityReportAvailable(report);
9287 } catch (RemoteException ex) {
9288 loge("Error invoking onConnectivityReport", ex);
9289 }
9290 }
9291 }
9292
9293 private void handleDataStallSuspected(
9294 @NonNull NetworkAgentInfo nai, long timestampMillis, int detectionMethod,
9295 @NonNull PersistableBundle extras) {
9296 final NetworkCapabilities networkCapabilities =
9297 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
9298 final DataStallReport report =
9299 new DataStallReport(
9300 nai.network,
9301 timestampMillis,
9302 detectionMethod,
9303 nai.linkProperties,
9304 networkCapabilities,
9305 extras);
9306 final List<IConnectivityDiagnosticsCallback> results =
9307 getMatchingPermissionedCallbacks(nai);
9308 for (final IConnectivityDiagnosticsCallback cb : results) {
9309 try {
9310 cb.onDataStallSuspected(report);
9311 } catch (RemoteException ex) {
9312 loge("Error invoking onDataStallSuspected", ex);
9313 }
9314 }
9315 }
9316
9317 private void handleNetworkConnectivityReported(
9318 @NonNull NetworkAgentInfo nai, boolean connectivity) {
9319 final List<IConnectivityDiagnosticsCallback> results =
9320 getMatchingPermissionedCallbacks(nai);
9321 for (final IConnectivityDiagnosticsCallback cb : results) {
9322 try {
9323 cb.onNetworkConnectivityReported(nai.network, connectivity);
9324 } catch (RemoteException ex) {
9325 loge("Error invoking onNetworkConnectivityReported", ex);
9326 }
9327 }
9328 }
9329
9330 private NetworkCapabilities getNetworkCapabilitiesWithoutUids(@NonNull NetworkCapabilities nc) {
9331 final NetworkCapabilities sanitized = new NetworkCapabilities(nc,
9332 NetworkCapabilities.REDACT_ALL);
9333 sanitized.setUids(null);
9334 sanitized.setAdministratorUids(new int[0]);
9335 sanitized.setOwnerUid(Process.INVALID_UID);
9336 return sanitized;
9337 }
9338
9339 private List<IConnectivityDiagnosticsCallback> getMatchingPermissionedCallbacks(
9340 @NonNull NetworkAgentInfo nai) {
9341 final List<IConnectivityDiagnosticsCallback> results = new ArrayList<>();
9342 for (Entry<IBinder, ConnectivityDiagnosticsCallbackInfo> entry :
9343 mConnectivityDiagnosticsCallbacks.entrySet()) {
9344 final ConnectivityDiagnosticsCallbackInfo cbInfo = entry.getValue();
9345 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
9346 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0).
9347 if (nai.satisfies(nri.mRequests.get(0))) {
9348 if (checkConnectivityDiagnosticsPermissions(
9349 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
9350 results.add(entry.getValue().mCb);
9351 }
9352 }
9353 }
9354 return results;
9355 }
9356
Treehugger Robot27b68882021-06-07 19:42:39 +00009357 private boolean isLocationPermissionRequiredForConnectivityDiagnostics(
9358 @NonNull NetworkAgentInfo nai) {
9359 // TODO(b/188483916): replace with a transport-agnostic location-aware check
9360 return nai.networkCapabilities.hasTransport(TRANSPORT_WIFI);
9361 }
9362
Cody Kesting0b4be022021-05-20 22:57:07 +00009363 private boolean hasLocationPermission(String packageName, int uid) {
9364 // LocationPermissionChecker#checkLocationPermission can throw SecurityException if the uid
9365 // and package name don't match. Throwing on the CS thread is not acceptable, so wrap the
9366 // call in a try-catch.
9367 try {
9368 if (!mLocationPermissionChecker.checkLocationPermission(
9369 packageName, null /* featureId */, uid, null /* message */)) {
9370 return false;
9371 }
9372 } catch (SecurityException e) {
9373 return false;
9374 }
9375
9376 return true;
9377 }
9378
9379 private boolean ownsVpnRunningOverNetwork(int uid, Network network) {
9380 for (NetworkAgentInfo virtual : mNetworkAgentInfos) {
Treehugger Robot4703a8c2021-07-02 13:55:33 +00009381 if (virtual.propagateUnderlyingCapabilities()
Cody Kesting0b4be022021-05-20 22:57:07 +00009382 && virtual.networkCapabilities.getOwnerUid() == uid
9383 && CollectionUtils.contains(virtual.declaredUnderlyingNetworks, network)) {
9384 return true;
9385 }
9386 }
9387
9388 return false;
9389 }
9390
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00009391 @VisibleForTesting
9392 boolean checkConnectivityDiagnosticsPermissions(
9393 int callbackPid, int callbackUid, NetworkAgentInfo nai, String callbackPackageName) {
9394 if (checkNetworkStackPermission(callbackPid, callbackUid)) {
9395 return true;
9396 }
9397
Cody Kesting0b4be022021-05-20 22:57:07 +00009398 // Administrator UIDs also contains the Owner UID
9399 final int[] administratorUids = nai.networkCapabilities.getAdministratorUids();
9400 if (!CollectionUtils.contains(administratorUids, callbackUid)
9401 && !ownsVpnRunningOverNetwork(callbackUid, nai.network)) {
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00009402 return false;
9403 }
9404
Treehugger Robot27b68882021-06-07 19:42:39 +00009405 return !isLocationPermissionRequiredForConnectivityDiagnostics(nai)
9406 || hasLocationPermission(callbackPackageName, callbackUid);
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00009407 }
9408
9409 @Override
9410 public void registerConnectivityDiagnosticsCallback(
9411 @NonNull IConnectivityDiagnosticsCallback callback,
9412 @NonNull NetworkRequest request,
9413 @NonNull String callingPackageName) {
9414 if (request.legacyType != TYPE_NONE) {
9415 throw new IllegalArgumentException("ConnectivityManager.TYPE_* are deprecated."
9416 + " Please use NetworkCapabilities instead.");
9417 }
9418 final int callingUid = mDeps.getCallingUid();
9419 mAppOpsManager.checkPackage(callingUid, callingPackageName);
9420
9421 // This NetworkCapabilities is only used for matching to Networks. Clear out its owner uid
9422 // and administrator uids to be safe.
9423 final NetworkCapabilities nc = new NetworkCapabilities(request.networkCapabilities);
9424 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
9425
9426 final NetworkRequest requestWithId =
9427 new NetworkRequest(
9428 nc, TYPE_NONE, nextNetworkRequestId(), NetworkRequest.Type.LISTEN);
9429
9430 // NetworkRequestInfos created here count towards MAX_NETWORK_REQUESTS_PER_UID limit.
9431 //
9432 // nri is not bound to the death of callback. Instead, callback.bindToDeath() is set in
9433 // handleRegisterConnectivityDiagnosticsCallback(). nri will be cleaned up as part of the
9434 // callback's binder death.
9435 final NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, requestWithId);
9436 final ConnectivityDiagnosticsCallbackInfo cbInfo =
9437 new ConnectivityDiagnosticsCallbackInfo(callback, nri, callingPackageName);
9438
9439 mConnectivityDiagnosticsHandler.sendMessage(
9440 mConnectivityDiagnosticsHandler.obtainMessage(
9441 ConnectivityDiagnosticsHandler
9442 .EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
9443 cbInfo));
9444 }
9445
9446 @Override
9447 public void unregisterConnectivityDiagnosticsCallback(
9448 @NonNull IConnectivityDiagnosticsCallback callback) {
9449 Objects.requireNonNull(callback, "callback must be non-null");
9450 mConnectivityDiagnosticsHandler.sendMessage(
9451 mConnectivityDiagnosticsHandler.obtainMessage(
9452 ConnectivityDiagnosticsHandler
9453 .EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
9454 mDeps.getCallingUid(),
9455 0,
9456 callback));
9457 }
9458
9459 @Override
9460 public void simulateDataStall(int detectionMethod, long timestampMillis,
9461 @NonNull Network network, @NonNull PersistableBundle extras) {
9462 enforceAnyPermissionOf(android.Manifest.permission.MANAGE_TEST_NETWORKS,
9463 android.Manifest.permission.NETWORK_STACK);
9464 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
9465 if (!nc.hasTransport(TRANSPORT_TEST)) {
9466 throw new SecurityException("Data Stall simluation is only possible for test networks");
9467 }
9468
9469 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
9470 if (nai == null || nai.creatorUid != mDeps.getCallingUid()) {
9471 throw new SecurityException("Data Stall simulation is only possible for network "
9472 + "creators");
9473 }
9474
9475 // Instead of passing the data stall directly to the ConnectivityDiagnostics handler, treat
9476 // this as a Data Stall received directly from NetworkMonitor. This requires wrapping the
9477 // Data Stall information as a DataStallReportParcelable and passing to
9478 // #notifyDataStallSuspected. This ensures that unknown Data Stall detection methods are
9479 // still passed to ConnectivityDiagnostics (with new detection methods masked).
9480 final DataStallReportParcelable p = new DataStallReportParcelable();
9481 p.timestampMillis = timestampMillis;
9482 p.detectionMethod = detectionMethod;
9483
9484 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
9485 p.dnsConsecutiveTimeouts = extras.getInt(KEY_DNS_CONSECUTIVE_TIMEOUTS);
9486 }
9487 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
9488 p.tcpPacketFailRate = extras.getInt(KEY_TCP_PACKET_FAIL_RATE);
9489 p.tcpMetricsCollectionPeriodMillis = extras.getInt(
9490 KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS);
9491 }
9492
9493 notifyDataStallSuspected(p, network.getNetId());
9494 }
9495
9496 private class NetdCallback extends BaseNetdUnsolicitedEventListener {
9497 @Override
9498 public void onInterfaceClassActivityChanged(boolean isActive, int transportType,
9499 long timestampNs, int uid) {
9500 mNetworkActivityTracker.setAndReportNetworkActive(isActive, transportType, timestampNs);
9501 }
9502
9503 @Override
9504 public void onInterfaceLinkStateChanged(String iface, boolean up) {
9505 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
9506 nai.clatd.interfaceLinkStateChanged(iface, up);
9507 }
9508 }
9509
9510 @Override
9511 public void onInterfaceRemoved(String iface) {
9512 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
9513 nai.clatd.interfaceRemoved(iface);
9514 }
9515 }
9516 }
9517
9518 private final LegacyNetworkActivityTracker mNetworkActivityTracker;
9519
9520 /**
9521 * Class used for updating network activity tracking with netd and notify network activity
9522 * changes.
9523 */
9524 private static final class LegacyNetworkActivityTracker {
9525 private static final int NO_UID = -1;
9526 private final Context mContext;
9527 private final INetd mNetd;
9528 private final RemoteCallbackList<INetworkActivityListener> mNetworkActivityListeners =
9529 new RemoteCallbackList<>();
9530 // Indicate the current system default network activity is active or not.
9531 @GuardedBy("mActiveIdleTimers")
9532 private boolean mNetworkActive;
9533 @GuardedBy("mActiveIdleTimers")
9534 private final ArrayMap<String, IdleTimerParams> mActiveIdleTimers = new ArrayMap();
9535 private final Handler mHandler;
9536
9537 private class IdleTimerParams {
9538 public final int timeout;
9539 public final int transportType;
9540
9541 IdleTimerParams(int timeout, int transport) {
9542 this.timeout = timeout;
9543 this.transportType = transport;
9544 }
9545 }
9546
9547 LegacyNetworkActivityTracker(@NonNull Context context, @NonNull Handler handler,
9548 @NonNull INetd netd) {
9549 mContext = context;
9550 mNetd = netd;
9551 mHandler = handler;
9552 }
9553
9554 public void setAndReportNetworkActive(boolean active, int transportType, long tsNanos) {
9555 sendDataActivityBroadcast(transportTypeToLegacyType(transportType), active, tsNanos);
9556 synchronized (mActiveIdleTimers) {
9557 mNetworkActive = active;
9558 // If there are no idle timers, it means that system is not monitoring
9559 // activity, so the system default network for those default network
9560 // unspecified apps is always considered active.
9561 //
9562 // TODO: If the mActiveIdleTimers is empty, netd will actually not send
9563 // any network activity change event. Whenever this event is received,
9564 // the mActiveIdleTimers should be always not empty. The legacy behavior
9565 // is no-op. Remove to refer to mNetworkActive only.
9566 if (mNetworkActive || mActiveIdleTimers.isEmpty()) {
9567 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REPORT_NETWORK_ACTIVITY));
9568 }
9569 }
9570 }
9571
9572 // The network activity should only be updated from ConnectivityService handler thread
9573 // when mActiveIdleTimers lock is held.
9574 @GuardedBy("mActiveIdleTimers")
9575 private void reportNetworkActive() {
9576 final int length = mNetworkActivityListeners.beginBroadcast();
9577 if (DDBG) log("reportNetworkActive, notify " + length + " listeners");
9578 try {
9579 for (int i = 0; i < length; i++) {
9580 try {
9581 mNetworkActivityListeners.getBroadcastItem(i).onNetworkActive();
9582 } catch (RemoteException | RuntimeException e) {
9583 loge("Fail to send network activie to listener " + e);
9584 }
9585 }
9586 } finally {
9587 mNetworkActivityListeners.finishBroadcast();
9588 }
9589 }
9590
9591 @GuardedBy("mActiveIdleTimers")
9592 public void handleReportNetworkActivity() {
9593 synchronized (mActiveIdleTimers) {
9594 reportNetworkActive();
9595 }
9596 }
9597
9598 // This is deprecated and only to support legacy use cases.
9599 private int transportTypeToLegacyType(int type) {
9600 switch (type) {
9601 case NetworkCapabilities.TRANSPORT_CELLULAR:
9602 return TYPE_MOBILE;
9603 case NetworkCapabilities.TRANSPORT_WIFI:
9604 return TYPE_WIFI;
9605 case NetworkCapabilities.TRANSPORT_BLUETOOTH:
9606 return TYPE_BLUETOOTH;
9607 case NetworkCapabilities.TRANSPORT_ETHERNET:
9608 return TYPE_ETHERNET;
9609 default:
9610 loge("Unexpected transport in transportTypeToLegacyType: " + type);
9611 }
9612 return ConnectivityManager.TYPE_NONE;
9613 }
9614
9615 public void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
9616 final Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
9617 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
9618 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
9619 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
9620 final long ident = Binder.clearCallingIdentity();
9621 try {
9622 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
9623 RECEIVE_DATA_ACTIVITY_CHANGE,
9624 null /* resultReceiver */,
9625 null /* scheduler */,
9626 0 /* initialCode */,
9627 null /* initialData */,
9628 null /* initialExtra */);
9629 } finally {
9630 Binder.restoreCallingIdentity(ident);
9631 }
9632 }
9633
9634 /**
9635 * Setup data activity tracking for the given network.
9636 *
9637 * Every {@code setupDataActivityTracking} should be paired with a
9638 * {@link #removeDataActivityTracking} for cleanup.
9639 */
9640 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
9641 final String iface = networkAgent.linkProperties.getInterfaceName();
9642
9643 final int timeout;
9644 final int type;
9645
9646 if (networkAgent.networkCapabilities.hasTransport(
9647 NetworkCapabilities.TRANSPORT_CELLULAR)) {
9648 timeout = Settings.Global.getInt(mContext.getContentResolver(),
9649 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_MOBILE,
9650 10);
9651 type = NetworkCapabilities.TRANSPORT_CELLULAR;
9652 } else if (networkAgent.networkCapabilities.hasTransport(
9653 NetworkCapabilities.TRANSPORT_WIFI)) {
9654 timeout = Settings.Global.getInt(mContext.getContentResolver(),
9655 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_WIFI,
9656 15);
9657 type = NetworkCapabilities.TRANSPORT_WIFI;
9658 } else {
9659 return; // do not track any other networks
9660 }
9661
9662 updateRadioPowerState(true /* isActive */, type);
9663
9664 if (timeout > 0 && iface != null) {
9665 try {
9666 synchronized (mActiveIdleTimers) {
9667 // Networks start up.
9668 mNetworkActive = true;
9669 mActiveIdleTimers.put(iface, new IdleTimerParams(timeout, type));
9670 mNetd.idletimerAddInterface(iface, timeout, Integer.toString(type));
9671 reportNetworkActive();
9672 }
9673 } catch (Exception e) {
9674 // You shall not crash!
9675 loge("Exception in setupDataActivityTracking " + e);
9676 }
9677 }
9678 }
9679
9680 /**
9681 * Remove data activity tracking when network disconnects.
9682 */
9683 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
9684 final String iface = networkAgent.linkProperties.getInterfaceName();
9685 final NetworkCapabilities caps = networkAgent.networkCapabilities;
9686
9687 if (iface == null) return;
9688
9689 final int type;
9690 if (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
9691 type = NetworkCapabilities.TRANSPORT_CELLULAR;
9692 } else if (caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
9693 type = NetworkCapabilities.TRANSPORT_WIFI;
9694 } else {
9695 return; // do not track any other networks
9696 }
9697
9698 try {
9699 updateRadioPowerState(false /* isActive */, type);
9700 synchronized (mActiveIdleTimers) {
9701 final IdleTimerParams params = mActiveIdleTimers.remove(iface);
9702 // The call fails silently if no idle timer setup for this interface
9703 mNetd.idletimerRemoveInterface(iface, params.timeout,
9704 Integer.toString(params.transportType));
9705 }
9706 } catch (Exception e) {
9707 // You shall not crash!
9708 loge("Exception in removeDataActivityTracking " + e);
9709 }
9710 }
9711
9712 /**
9713 * Update data activity tracking when network state is updated.
9714 */
9715 public void updateDataActivityTracking(NetworkAgentInfo newNetwork,
9716 NetworkAgentInfo oldNetwork) {
9717 if (newNetwork != null) {
9718 setupDataActivityTracking(newNetwork);
9719 }
9720 if (oldNetwork != null) {
9721 removeDataActivityTracking(oldNetwork);
9722 }
9723 }
9724
9725 private void updateRadioPowerState(boolean isActive, int transportType) {
9726 final BatteryStatsManager bs = mContext.getSystemService(BatteryStatsManager.class);
9727 switch (transportType) {
9728 case NetworkCapabilities.TRANSPORT_CELLULAR:
9729 bs.reportMobileRadioPowerState(isActive, NO_UID);
9730 break;
9731 case NetworkCapabilities.TRANSPORT_WIFI:
9732 bs.reportWifiRadioPowerState(isActive, NO_UID);
9733 break;
9734 default:
9735 logw("Untracked transport type:" + transportType);
9736 }
9737 }
9738
9739 public boolean isDefaultNetworkActive() {
9740 synchronized (mActiveIdleTimers) {
9741 // If there are no idle timers, it means that system is not monitoring activity,
9742 // so the default network is always considered active.
9743 //
9744 // TODO : Distinguish between the cases where mActiveIdleTimers is empty because
9745 // tracking is disabled (negative idle timer value configured), or no active default
9746 // network. In the latter case, this reports active but it should report inactive.
9747 return mNetworkActive || mActiveIdleTimers.isEmpty();
9748 }
9749 }
9750
9751 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
9752 mNetworkActivityListeners.register(l);
9753 }
9754
9755 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
9756 mNetworkActivityListeners.unregister(l);
9757 }
9758
9759 public void dump(IndentingPrintWriter pw) {
9760 synchronized (mActiveIdleTimers) {
9761 pw.print("mNetworkActive="); pw.println(mNetworkActive);
9762 pw.println("Idle timers:");
9763 for (HashMap.Entry<String, IdleTimerParams> ent : mActiveIdleTimers.entrySet()) {
9764 pw.print(" "); pw.print(ent.getKey()); pw.println(":");
9765 final IdleTimerParams params = ent.getValue();
9766 pw.print(" timeout="); pw.print(params.timeout);
9767 pw.print(" type="); pw.println(params.transportType);
9768 }
9769 }
9770 }
9771 }
9772
9773 /**
9774 * Registers {@link QosSocketFilter} with {@link IQosCallback}.
9775 *
9776 * @param socketInfo the socket information
9777 * @param callback the callback to register
9778 */
9779 @Override
9780 public void registerQosSocketCallback(@NonNull final QosSocketInfo socketInfo,
9781 @NonNull final IQosCallback callback) {
9782 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(socketInfo.getNetwork());
9783 if (nai == null || nai.networkCapabilities == null) {
9784 try {
9785 callback.onError(QosCallbackException.EX_TYPE_FILTER_NETWORK_RELEASED);
9786 } catch (final RemoteException ex) {
9787 loge("registerQosCallbackInternal: RemoteException", ex);
9788 }
9789 return;
9790 }
9791 registerQosCallbackInternal(new QosSocketFilter(socketInfo), callback, nai);
9792 }
9793
9794 /**
9795 * Register a {@link IQosCallback} with base {@link QosFilter}.
9796 *
9797 * @param filter the filter to register
9798 * @param callback the callback to register
9799 * @param nai the agent information related to the filter's network
9800 */
9801 @VisibleForTesting
9802 public void registerQosCallbackInternal(@NonNull final QosFilter filter,
9803 @NonNull final IQosCallback callback, @NonNull final NetworkAgentInfo nai) {
9804 if (filter == null) throw new IllegalArgumentException("filter must be non-null");
9805 if (callback == null) throw new IllegalArgumentException("callback must be non-null");
9806
9807 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
9808 enforceConnectivityRestrictedNetworksPermission();
9809 }
9810 mQosCallbackTracker.registerCallback(callback, filter, nai);
9811 }
9812
9813 /**
9814 * Unregisters the given callback.
9815 *
9816 * @param callback the callback to unregister
9817 */
9818 @Override
9819 public void unregisterQosCallback(@NonNull final IQosCallback callback) {
9820 Objects.requireNonNull(callback, "callback must be non-null");
9821 mQosCallbackTracker.unregisterCallback(callback);
9822 }
9823
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00009824 /**
9825 * Request that a user profile is put by default on a network matching a given preference.
9826 *
9827 * See the documentation for the individual preferences for a description of the supported
9828 * behaviors.
9829 *
9830 * @param profile the profile concerned.
9831 * @param preference the preference for this profile, as one of the PROFILE_NETWORK_PREFERENCE_*
9832 * constants.
9833 * @param listener an optional listener to listen for completion of the operation.
9834 */
9835 @Override
9836 public void setProfileNetworkPreference(@NonNull final UserHandle profile,
9837 @ConnectivityManager.ProfileNetworkPreference final int preference,
9838 @Nullable final IOnCompleteListener listener) {
9839 Objects.requireNonNull(profile);
9840 PermissionUtils.enforceNetworkStackPermission(mContext);
9841 if (DBG) {
9842 log("setProfileNetworkPreference " + profile + " to " + preference);
9843 }
9844 if (profile.getIdentifier() < 0) {
9845 throw new IllegalArgumentException("Must explicitly specify a user handle ("
9846 + "UserHandle.CURRENT not supported)");
9847 }
9848 final UserManager um = mContext.getSystemService(UserManager.class);
9849 if (!um.isManagedProfile(profile.getIdentifier())) {
9850 throw new IllegalArgumentException("Profile must be a managed profile");
9851 }
paulhude5efb92021-05-26 21:56:03 +08009852
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00009853 final NetworkCapabilities nc;
9854 switch (preference) {
9855 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT:
9856 nc = null;
9857 break;
9858 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE:
9859 final UidRange uids = UidRange.createForUser(profile);
9860 nc = createDefaultNetworkCapabilitiesForUidRange(uids);
9861 nc.addCapability(NET_CAPABILITY_ENTERPRISE);
9862 nc.removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
9863 break;
9864 default:
9865 throw new IllegalArgumentException(
9866 "Invalid preference in setProfileNetworkPreference");
9867 }
9868 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_PROFILE_NETWORK_PREFERENCE,
9869 new Pair<>(new ProfileNetworkPreferences.Preference(profile, nc), listener)));
9870 }
9871
9872 private void validateNetworkCapabilitiesOfProfileNetworkPreference(
9873 @Nullable final NetworkCapabilities nc) {
9874 if (null == nc) return; // Null caps are always allowed. It means to remove the setting.
9875 ensureRequestableCapabilities(nc);
9876 }
9877
9878 private ArraySet<NetworkRequestInfo> createNrisFromProfileNetworkPreferences(
9879 @NonNull final ProfileNetworkPreferences prefs) {
9880 final ArraySet<NetworkRequestInfo> result = new ArraySet<>();
9881 for (final ProfileNetworkPreferences.Preference pref : prefs.preferences) {
9882 // The NRI for a user should be comprised of two layers:
9883 // - The request for the capabilities
9884 // - The request for the default network, for fallback. Create an image of it to
9885 // have the correct UIDs in it (also a request can only be part of one NRI, because
9886 // of lookups in 1:1 associations like mNetworkRequests).
9887 // Note that denying a fallback can be implemented simply by not adding the second
9888 // request.
9889 final ArrayList<NetworkRequest> nrs = new ArrayList<>();
9890 nrs.add(createNetworkRequest(NetworkRequest.Type.REQUEST, pref.capabilities));
9891 nrs.add(createDefaultInternetRequestForTransport(
9892 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
9893 setNetworkRequestUids(nrs, UidRange.fromIntRanges(pref.capabilities.getUids()));
paulhuc2198772021-05-26 15:19:20 +08009894 final NetworkRequestInfo nri = new NetworkRequestInfo(Process.myUid(), nrs,
paulhude5efb92021-05-26 21:56:03 +08009895 PREFERENCE_PRIORITY_PROFILE);
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00009896 result.add(nri);
9897 }
9898 return result;
9899 }
9900
9901 private void handleSetProfileNetworkPreference(
9902 @NonNull final ProfileNetworkPreferences.Preference preference,
9903 @Nullable final IOnCompleteListener listener) {
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00009904 validateNetworkCapabilitiesOfProfileNetworkPreference(preference.capabilities);
9905
9906 mProfileNetworkPreferences = mProfileNetworkPreferences.plus(preference);
9907 mSystemNetworkRequestCounter.transact(
9908 mDeps.getCallingUid(), mProfileNetworkPreferences.preferences.size(),
9909 () -> {
9910 final ArraySet<NetworkRequestInfo> nris =
9911 createNrisFromProfileNetworkPreferences(mProfileNetworkPreferences);
paulhude5efb92021-05-26 21:56:03 +08009912 replaceDefaultNetworkRequestsForPreference(nris, PREFERENCE_PRIORITY_PROFILE);
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00009913 });
9914 // Finally, rematch.
9915 rematchAllNetworksAndRequests();
9916
9917 if (null != listener) {
9918 try {
9919 listener.onComplete();
9920 } catch (RemoteException e) {
9921 loge("Listener for setProfileNetworkPreference has died");
9922 }
9923 }
9924 }
9925
paulhu71ad4f12021-05-25 14:56:27 +08009926 @VisibleForTesting
9927 @NonNull
9928 ArraySet<NetworkRequestInfo> createNrisFromMobileDataPreferredUids(
9929 @NonNull final Set<Integer> uids) {
9930 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
9931 if (uids.size() == 0) {
9932 // Should not create NetworkRequestInfo if no preferences. Without uid range in
9933 // NetworkRequestInfo, makeDefaultForApps() would treat it as a illegal NRI.
9934 if (DBG) log("Don't create NetworkRequestInfo because no preferences");
9935 return nris;
9936 }
9937
9938 final List<NetworkRequest> requests = new ArrayList<>();
9939 // The NRI should be comprised of two layers:
9940 // - The request for the mobile network preferred.
9941 // - The request for the default network, for fallback.
9942 requests.add(createDefaultInternetRequestForTransport(
Paul Hu07950df2021-07-02 01:44:52 +00009943 TRANSPORT_CELLULAR, NetworkRequest.Type.REQUEST));
paulhu71ad4f12021-05-25 14:56:27 +08009944 requests.add(createDefaultInternetRequestForTransport(
9945 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
9946 final Set<UidRange> ranges = new ArraySet<>();
9947 for (final int uid : uids) {
9948 ranges.add(new UidRange(uid, uid));
9949 }
9950 setNetworkRequestUids(requests, ranges);
paulhuc2198772021-05-26 15:19:20 +08009951 nris.add(new NetworkRequestInfo(Process.myUid(), requests,
paulhude5efb92021-05-26 21:56:03 +08009952 PREFERENCE_PRIORITY_MOBILE_DATA_PREFERERRED));
paulhu71ad4f12021-05-25 14:56:27 +08009953 return nris;
9954 }
9955
9956 private void handleMobileDataPreferredUidsChanged() {
paulhu71ad4f12021-05-25 14:56:27 +08009957 mMobileDataPreferredUids = ConnectivitySettingsManager.getMobileDataPreferredUids(mContext);
9958 mSystemNetworkRequestCounter.transact(
9959 mDeps.getCallingUid(), 1 /* numOfNewRequests */,
9960 () -> {
9961 final ArraySet<NetworkRequestInfo> nris =
9962 createNrisFromMobileDataPreferredUids(mMobileDataPreferredUids);
paulhude5efb92021-05-26 21:56:03 +08009963 replaceDefaultNetworkRequestsForPreference(nris,
9964 PREFERENCE_PRIORITY_MOBILE_DATA_PREFERERRED);
paulhu71ad4f12021-05-25 14:56:27 +08009965 });
9966 // Finally, rematch.
9967 rematchAllNetworksAndRequests();
9968 }
9969
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00009970 private void enforceAutomotiveDevice() {
9971 final boolean isAutomotiveDevice =
9972 mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE);
9973 if (!isAutomotiveDevice) {
9974 throw new UnsupportedOperationException(
9975 "setOemNetworkPreference() is only available on automotive devices.");
9976 }
9977 }
9978
9979 /**
9980 * Used by automotive devices to set the network preferences used to direct traffic at an
9981 * application level as per the given OemNetworkPreferences. An example use-case would be an
9982 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
9983 * vehicle via a particular network.
9984 *
9985 * Calling this will overwrite the existing preference.
9986 *
9987 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
9988 * @param listener {@link ConnectivityManager.OnCompleteListener} Listener used
9989 * to communicate completion of setOemNetworkPreference();
9990 */
9991 @Override
9992 public void setOemNetworkPreference(
9993 @NonNull final OemNetworkPreferences preference,
9994 @Nullable final IOnCompleteListener listener) {
9995
James Mattisb7ca0342021-06-16 01:30:05 +00009996 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
9997 // Only bypass the permission/device checks if this is a valid test request.
9998 if (isValidTestOemNetworkPreference(preference)) {
9999 enforceManageTestNetworksPermission();
10000 } else {
10001 enforceAutomotiveDevice();
10002 enforceOemNetworkPreferencesPermission();
10003 validateOemNetworkPreferences(preference);
10004 }
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +000010005
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +000010006 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_OEM_NETWORK_PREFERENCE,
10007 new Pair<>(preference, listener)));
10008 }
10009
James Mattisb7ca0342021-06-16 01:30:05 +000010010 /**
10011 * Check the validity of an OEM network preference to be used for testing purposes.
10012 * @param preference the preference to validate
10013 * @return true if this is a valid OEM network preference test request.
10014 */
10015 private boolean isValidTestOemNetworkPreference(
10016 @NonNull final OemNetworkPreferences preference) {
10017 // Allow for clearing of an existing OemNetworkPreference used for testing.
10018 // This isn't called on the handler thread so it is possible that mOemNetworkPreferences
10019 // changes after this check is complete. This is an unlikely scenario as calling of this API
10020 // is controlled by the OEM therefore the added complexity is not worth adding given those
10021 // circumstances. That said, it is an edge case to be aware of hence this comment.
10022 final boolean isValidTestClearPref = preference.getNetworkPreferences().size() == 0
10023 && isTestOemNetworkPreference(mOemNetworkPreferences);
10024 return isTestOemNetworkPreference(preference) || isValidTestClearPref;
10025 }
10026
10027 private boolean isTestOemNetworkPreference(@NonNull final OemNetworkPreferences preference) {
10028 final Map<String, Integer> prefMap = preference.getNetworkPreferences();
10029 return prefMap.size() == 1
10030 && (prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST)
10031 || prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST_ONLY));
10032 }
10033
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +000010034 private void validateOemNetworkPreferences(@NonNull OemNetworkPreferences preference) {
10035 for (@OemNetworkPreferences.OemNetworkPreference final int pref
10036 : preference.getNetworkPreferences().values()) {
James Mattisb7ca0342021-06-16 01:30:05 +000010037 if (pref <= 0 || OemNetworkPreferences.OEM_NETWORK_PREFERENCE_MAX < pref) {
10038 throw new IllegalArgumentException(
10039 OemNetworkPreferences.oemNetworkPreferenceToString(pref)
10040 + " is an invalid value.");
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +000010041 }
10042 }
10043 }
10044
10045 private void handleSetOemNetworkPreference(
10046 @NonNull final OemNetworkPreferences preference,
10047 @Nullable final IOnCompleteListener listener) {
10048 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
10049 if (DBG) {
10050 log("set OEM network preferences :" + preference.toString());
10051 }
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +000010052
10053 mOemNetworkPreferencesLogs.log("UPDATE INITIATED: " + preference);
10054 final int uniquePreferenceCount = new ArraySet<>(
10055 preference.getNetworkPreferences().values()).size();
10056 mSystemNetworkRequestCounter.transact(
10057 mDeps.getCallingUid(), uniquePreferenceCount,
10058 () -> {
10059 final ArraySet<NetworkRequestInfo> nris =
10060 new OemNetworkRequestFactory()
10061 .createNrisFromOemNetworkPreferences(preference);
paulhude5efb92021-05-26 21:56:03 +080010062 replaceDefaultNetworkRequestsForPreference(nris, PREFERENCE_PRIORITY_OEM);
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +000010063 });
10064 mOemNetworkPreferences = preference;
10065
10066 if (null != listener) {
10067 try {
10068 listener.onComplete();
10069 } catch (RemoteException e) {
10070 loge("Can't send onComplete in handleSetOemNetworkPreference", e);
10071 }
10072 }
10073 }
10074
10075 private void replaceDefaultNetworkRequestsForPreference(
paulhude5efb92021-05-26 21:56:03 +080010076 @NonNull final Set<NetworkRequestInfo> nris, final int preferencePriority) {
10077 // Skip the requests which are set by other network preference. Because the uid range rules
10078 // should stay in netd.
10079 final Set<NetworkRequestInfo> requests = new ArraySet<>(mDefaultNetworkRequests);
10080 requests.removeIf(request -> request.mPreferencePriority != preferencePriority);
10081 handleRemoveNetworkRequests(requests);
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +000010082 addPerAppDefaultNetworkRequests(nris);
10083 }
10084
10085 private void addPerAppDefaultNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
10086 ensureRunningOnConnectivityServiceThread();
10087 mDefaultNetworkRequests.addAll(nris);
10088 final ArraySet<NetworkRequestInfo> perAppCallbackRequestsToUpdate =
10089 getPerAppCallbackRequestsToUpdate();
10090 final ArraySet<NetworkRequestInfo> nrisToRegister = new ArraySet<>(nris);
10091 mSystemNetworkRequestCounter.transact(
10092 mDeps.getCallingUid(), perAppCallbackRequestsToUpdate.size(),
10093 () -> {
10094 nrisToRegister.addAll(
10095 createPerAppCallbackRequestsToRegister(perAppCallbackRequestsToUpdate));
10096 handleRemoveNetworkRequests(perAppCallbackRequestsToUpdate);
10097 handleRegisterNetworkRequests(nrisToRegister);
10098 });
10099 }
10100
10101 /**
10102 * All current requests that are tracking the default network need to be assessed as to whether
10103 * or not the current set of per-application default requests will be changing their default
10104 * network. If so, those requests will need to be updated so that they will send callbacks for
10105 * default network changes at the appropriate time. Additionally, those requests tracking the
10106 * default that were previously updated by this flow will need to be reassessed.
10107 * @return the nris which will need to be updated.
10108 */
10109 private ArraySet<NetworkRequestInfo> getPerAppCallbackRequestsToUpdate() {
10110 final ArraySet<NetworkRequestInfo> defaultCallbackRequests = new ArraySet<>();
10111 // Get the distinct nris to check since for multilayer requests, it is possible to have the
10112 // same nri in the map's values for each of its NetworkRequest objects.
10113 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>(mNetworkRequests.values());
10114 for (final NetworkRequestInfo nri : nris) {
10115 // Include this nri if it is currently being tracked.
10116 if (isPerAppTrackedNri(nri)) {
10117 defaultCallbackRequests.add(nri);
10118 continue;
10119 }
10120 // We only track callbacks for requests tracking the default.
10121 if (NetworkRequest.Type.TRACK_DEFAULT != nri.mRequests.get(0).type) {
10122 continue;
10123 }
10124 // Include this nri if it will be tracked by the new per-app default requests.
10125 final boolean isNriGoingToBeTracked =
10126 getDefaultRequestTrackingUid(nri.mAsUid) != mDefaultRequest;
10127 if (isNriGoingToBeTracked) {
10128 defaultCallbackRequests.add(nri);
10129 }
10130 }
10131 return defaultCallbackRequests;
10132 }
10133
10134 /**
10135 * Create nris for those network requests that are currently tracking the default network that
10136 * are being controlled by a per-application default.
10137 * @param perAppCallbackRequestsForUpdate the baseline network requests to be used as the
10138 * foundation when creating the nri. Important items include the calling uid's original
10139 * NetworkRequest to be used when mapping callbacks as well as the caller's uid and name. These
10140 * requests are assumed to have already been validated as needing to be updated.
10141 * @return the Set of nris to use when registering network requests.
10142 */
10143 private ArraySet<NetworkRequestInfo> createPerAppCallbackRequestsToRegister(
10144 @NonNull final ArraySet<NetworkRequestInfo> perAppCallbackRequestsForUpdate) {
10145 final ArraySet<NetworkRequestInfo> callbackRequestsToRegister = new ArraySet<>();
10146 for (final NetworkRequestInfo callbackRequest : perAppCallbackRequestsForUpdate) {
10147 final NetworkRequestInfo trackingNri =
10148 getDefaultRequestTrackingUid(callbackRequest.mAsUid);
10149
10150 // If this nri is not being tracked, the change it back to an untracked nri.
10151 if (trackingNri == mDefaultRequest) {
10152 callbackRequestsToRegister.add(new NetworkRequestInfo(
10153 callbackRequest,
10154 Collections.singletonList(callbackRequest.getNetworkRequestForCallback())));
10155 continue;
10156 }
10157
10158 final NetworkRequest request = callbackRequest.mRequests.get(0);
10159 callbackRequestsToRegister.add(new NetworkRequestInfo(
10160 callbackRequest,
10161 copyNetworkRequestsForUid(
10162 trackingNri.mRequests, callbackRequest.mAsUid,
10163 callbackRequest.mUid, request.getRequestorPackageName())));
10164 }
10165 return callbackRequestsToRegister;
10166 }
10167
10168 private static void setNetworkRequestUids(@NonNull final List<NetworkRequest> requests,
10169 @NonNull final Set<UidRange> uids) {
10170 for (final NetworkRequest req : requests) {
10171 req.networkCapabilities.setUids(UidRange.toIntRanges(uids));
10172 }
10173 }
10174
10175 /**
10176 * Class used to generate {@link NetworkRequestInfo} based off of {@link OemNetworkPreferences}.
10177 */
10178 @VisibleForTesting
10179 final class OemNetworkRequestFactory {
10180 ArraySet<NetworkRequestInfo> createNrisFromOemNetworkPreferences(
10181 @NonNull final OemNetworkPreferences preference) {
10182 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
10183 final SparseArray<Set<Integer>> uids =
10184 createUidsFromOemNetworkPreferences(preference);
10185 for (int i = 0; i < uids.size(); i++) {
10186 final int key = uids.keyAt(i);
10187 final Set<Integer> value = uids.valueAt(i);
10188 final NetworkRequestInfo nri = createNriFromOemNetworkPreferences(key, value);
10189 // No need to add an nri without any requests.
10190 if (0 == nri.mRequests.size()) {
10191 continue;
10192 }
10193 nris.add(nri);
10194 }
10195
10196 return nris;
10197 }
10198
10199 private SparseArray<Set<Integer>> createUidsFromOemNetworkPreferences(
10200 @NonNull final OemNetworkPreferences preference) {
Lorenzo Colitti659a0e12021-06-14 06:32:56 +000010201 final SparseArray<Set<Integer>> prefToUids = new SparseArray<>();
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +000010202 final PackageManager pm = mContext.getPackageManager();
10203 final List<UserHandle> users =
10204 mContext.getSystemService(UserManager.class).getUserHandles(true);
10205 if (null == users || users.size() == 0) {
10206 if (VDBG || DDBG) {
10207 log("No users currently available for setting the OEM network preference.");
10208 }
Lorenzo Colitti659a0e12021-06-14 06:32:56 +000010209 return prefToUids;
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +000010210 }
10211 for (final Map.Entry<String, Integer> entry :
10212 preference.getNetworkPreferences().entrySet()) {
10213 @OemNetworkPreferences.OemNetworkPreference final int pref = entry.getValue();
Lorenzo Colitti659a0e12021-06-14 06:32:56 +000010214 // Add the rules for all users as this policy is device wide.
10215 for (final UserHandle user : users) {
10216 try {
10217 final int uid = pm.getApplicationInfoAsUser(entry.getKey(), 0, user).uid;
10218 if (!prefToUids.contains(pref)) {
10219 prefToUids.put(pref, new ArraySet<>());
10220 }
10221 prefToUids.get(pref).add(uid);
10222 } catch (PackageManager.NameNotFoundException e) {
10223 // Although this may seem like an error scenario, it is ok that uninstalled
10224 // packages are sent on a network preference as the system will watch for
10225 // package installations associated with this network preference and update
10226 // accordingly. This is done to minimize race conditions on app install.
10227 continue;
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +000010228 }
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +000010229 }
10230 }
Lorenzo Colitti659a0e12021-06-14 06:32:56 +000010231 return prefToUids;
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +000010232 }
10233
10234 private NetworkRequestInfo createNriFromOemNetworkPreferences(
10235 @OemNetworkPreferences.OemNetworkPreference final int preference,
10236 @NonNull final Set<Integer> uids) {
10237 final List<NetworkRequest> requests = new ArrayList<>();
10238 // Requests will ultimately be evaluated by order of insertion therefore it matters.
10239 switch (preference) {
10240 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID:
10241 requests.add(createUnmeteredNetworkRequest());
10242 requests.add(createOemPaidNetworkRequest());
10243 requests.add(createDefaultInternetRequestForTransport(
10244 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
10245 break;
10246 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_NO_FALLBACK:
10247 requests.add(createUnmeteredNetworkRequest());
10248 requests.add(createOemPaidNetworkRequest());
10249 break;
10250 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_ONLY:
10251 requests.add(createOemPaidNetworkRequest());
10252 break;
10253 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PRIVATE_ONLY:
10254 requests.add(createOemPrivateNetworkRequest());
10255 break;
James Mattisb7ca0342021-06-16 01:30:05 +000010256 case OEM_NETWORK_PREFERENCE_TEST:
10257 requests.add(createUnmeteredNetworkRequest());
10258 requests.add(createTestNetworkRequest());
10259 requests.add(createDefaultRequest());
10260 break;
10261 case OEM_NETWORK_PREFERENCE_TEST_ONLY:
10262 requests.add(createTestNetworkRequest());
10263 break;
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +000010264 default:
10265 // This should never happen.
10266 throw new IllegalArgumentException("createNriFromOemNetworkPreferences()"
10267 + " called with invalid preference of " + preference);
10268 }
10269
James Mattisb7ca0342021-06-16 01:30:05 +000010270 final ArraySet<UidRange> ranges = new ArraySet<>();
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +000010271 for (final int uid : uids) {
10272 ranges.add(new UidRange(uid, uid));
10273 }
10274 setNetworkRequestUids(requests, ranges);
paulhude5efb92021-05-26 21:56:03 +080010275 return new NetworkRequestInfo(Process.myUid(), requests, PREFERENCE_PRIORITY_OEM);
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +000010276 }
10277
10278 private NetworkRequest createUnmeteredNetworkRequest() {
10279 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
10280 .addCapability(NET_CAPABILITY_NOT_METERED)
10281 .addCapability(NET_CAPABILITY_VALIDATED);
10282 return createNetworkRequest(NetworkRequest.Type.LISTEN, netcap);
10283 }
10284
10285 private NetworkRequest createOemPaidNetworkRequest() {
10286 // NET_CAPABILITY_OEM_PAID is a restricted capability.
10287 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
10288 .addCapability(NET_CAPABILITY_OEM_PAID)
10289 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
10290 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
10291 }
10292
10293 private NetworkRequest createOemPrivateNetworkRequest() {
10294 // NET_CAPABILITY_OEM_PRIVATE is a restricted capability.
10295 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
10296 .addCapability(NET_CAPABILITY_OEM_PRIVATE)
10297 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
10298 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
10299 }
10300
10301 private NetworkCapabilities createDefaultPerAppNetCap() {
James Mattisb7ca0342021-06-16 01:30:05 +000010302 final NetworkCapabilities netcap = new NetworkCapabilities();
10303 netcap.addCapability(NET_CAPABILITY_INTERNET);
10304 netcap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
10305 return netcap;
10306 }
10307
10308 private NetworkRequest createTestNetworkRequest() {
10309 final NetworkCapabilities netcap = new NetworkCapabilities();
10310 netcap.clearAll();
10311 netcap.addTransportType(TRANSPORT_TEST);
10312 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +000010313 }
10314 }
10315}