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