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