blob: b8f41296652d5cdc81efd314142c6f5d85979e51 [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) {
Cody Kestingf1120be2020-08-03 18:01:40 -07005094 if (nai == null
5095 || nai != getNetworkAgentInfoForNetwork(nai.network)
Cody Kestingf1120be2020-08-03 18:01:40 -07005096 || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00005097 return;
5098 }
5099 // Revalidate if the app report does not match our current validated state.
5100 if (hasConnectivity == nai.lastValidated) {
Cody Kestingf1120be2020-08-03 18:01:40 -07005101 mConnectivityDiagnosticsHandler.sendMessage(
5102 mConnectivityDiagnosticsHandler.obtainMessage(
5103 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
5104 new ReportedNetworkConnectivityInfo(
5105 hasConnectivity, false /* isNetworkRevalidating */, uid, nai)));
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00005106 return;
5107 }
5108 if (DBG) {
5109 int netid = nai.network.getNetId();
5110 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
5111 }
5112 // Validating a network that has not yet connected could result in a call to
5113 // rematchNetworkAndRequests() which is not meant to work on such networks.
5114 if (!nai.everConnected) {
5115 return;
5116 }
5117 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
5118 if (isNetworkWithCapabilitiesBlocked(nc, uid, false)) {
5119 return;
5120 }
Cody Kestingf1120be2020-08-03 18:01:40 -07005121
5122 // Send CONNECTIVITY_REPORTED event before re-validating the Network to force an ordering of
5123 // ConnDiags events. This ensures that #onNetworkConnectivityReported() will be called
5124 // before #onConnectivityReportAvailable(), which is called once Network evaluation is
5125 // completed.
5126 mConnectivityDiagnosticsHandler.sendMessage(
5127 mConnectivityDiagnosticsHandler.obtainMessage(
5128 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
5129 new ReportedNetworkConnectivityInfo(
5130 hasConnectivity, true /* isNetworkRevalidating */, uid, nai)));
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00005131 nai.networkMonitor().forceReevaluation(uid);
5132 }
5133
5134 // TODO: call into netd.
5135 private boolean queryUserAccess(int uid, Network network) {
5136 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5137 if (nai == null) return false;
5138
5139 // Any UID can use its default network.
5140 if (nai == getDefaultNetworkForUid(uid)) return true;
5141
5142 // Privileged apps can use any network.
5143 if (mPermissionMonitor.hasRestrictedNetworksPermission(uid)) {
5144 return true;
5145 }
5146
5147 // An unprivileged UID can use a VPN iff the VPN applies to it.
5148 if (nai.isVPN()) {
5149 return nai.networkCapabilities.appliesToUid(uid);
5150 }
5151
5152 // An unprivileged UID can bypass the VPN that applies to it only if it can protect its
5153 // sockets, i.e., if it is the owner.
5154 final NetworkAgentInfo vpn = getVpnForUid(uid);
5155 if (vpn != null && !vpn.networkAgentConfig.allowBypass
5156 && uid != vpn.networkCapabilities.getOwnerUid()) {
5157 return false;
5158 }
5159
5160 // The UID's permission must be at least sufficient for the network. Since the restricted
5161 // permission was already checked above, that just leaves background networks.
5162 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
5163 return mPermissionMonitor.hasUseBackgroundNetworksPermission(uid);
5164 }
5165
5166 // Unrestricted network. Anyone gets to use it.
5167 return true;
5168 }
5169
5170 /**
5171 * Returns information about the proxy a certain network is using. If given a null network, it
5172 * it will return the proxy for the bound network for the caller app or the default proxy if
5173 * none.
5174 *
5175 * @param network the network we want to get the proxy information for.
5176 * @return Proxy information if a network has a proxy configured, or otherwise null.
5177 */
5178 @Override
5179 public ProxyInfo getProxyForNetwork(Network network) {
5180 final ProxyInfo globalProxy = mProxyTracker.getGlobalProxy();
5181 if (globalProxy != null) return globalProxy;
5182 if (network == null) {
5183 // Get the network associated with the calling UID.
5184 final Network activeNetwork = getActiveNetworkForUidInternal(mDeps.getCallingUid(),
5185 true);
5186 if (activeNetwork == null) {
5187 return null;
5188 }
5189 return getLinkPropertiesProxyInfo(activeNetwork);
5190 } else if (mDeps.queryUserAccess(mDeps.getCallingUid(), network, this)) {
5191 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
5192 // caller may not have.
5193 return getLinkPropertiesProxyInfo(network);
5194 }
5195 // No proxy info available if the calling UID does not have network access.
5196 return null;
5197 }
5198
5199
5200 private ProxyInfo getLinkPropertiesProxyInfo(Network network) {
5201 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5202 if (nai == null) return null;
5203 synchronized (nai) {
5204 final ProxyInfo linkHttpProxy = nai.linkProperties.getHttpProxy();
5205 return linkHttpProxy == null ? null : new ProxyInfo(linkHttpProxy);
5206 }
5207 }
5208
5209 @Override
5210 public void setGlobalProxy(@Nullable final ProxyInfo proxyProperties) {
5211 PermissionUtils.enforceNetworkStackPermission(mContext);
5212 mProxyTracker.setGlobalProxy(proxyProperties);
5213 }
5214
5215 @Override
5216 @Nullable
5217 public ProxyInfo getGlobalProxy() {
5218 return mProxyTracker.getGlobalProxy();
5219 }
5220
5221 private void handleApplyDefaultProxy(ProxyInfo proxy) {
5222 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
5223 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
5224 proxy = null;
5225 }
5226 mProxyTracker.setDefaultProxy(proxy);
5227 }
5228
5229 // If the proxy has changed from oldLp to newLp, resend proxy broadcast. This method gets called
5230 // when any network changes proxy.
5231 // TODO: Remove usage of broadcast extras as they are deprecated and not applicable in a
5232 // multi-network world where an app might be bound to a non-default network.
5233 private void updateProxy(LinkProperties newLp, LinkProperties oldLp) {
5234 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
5235 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
5236
5237 if (!ProxyTracker.proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
5238 mProxyTracker.sendProxyBroadcast();
5239 }
5240 }
5241
5242 private static class SettingsObserver extends ContentObserver {
5243 final private HashMap<Uri, Integer> mUriEventMap;
5244 final private Context mContext;
5245 final private Handler mHandler;
5246
5247 SettingsObserver(Context context, Handler handler) {
5248 super(null);
5249 mUriEventMap = new HashMap<>();
5250 mContext = context;
5251 mHandler = handler;
5252 }
5253
5254 void observe(Uri uri, int what) {
5255 mUriEventMap.put(uri, what);
5256 final ContentResolver resolver = mContext.getContentResolver();
5257 resolver.registerContentObserver(uri, false, this);
5258 }
5259
5260 @Override
5261 public void onChange(boolean selfChange) {
5262 Log.wtf(TAG, "Should never be reached.");
5263 }
5264
5265 @Override
5266 public void onChange(boolean selfChange, Uri uri) {
5267 final Integer what = mUriEventMap.get(uri);
5268 if (what != null) {
5269 mHandler.obtainMessage(what).sendToTarget();
5270 } else {
5271 loge("No matching event to send for URI=" + uri);
5272 }
5273 }
5274 }
5275
5276 private static void log(String s) {
5277 Log.d(TAG, s);
5278 }
5279
5280 private static void logw(String s) {
5281 Log.w(TAG, s);
5282 }
5283
5284 private static void logwtf(String s) {
5285 Log.wtf(TAG, s);
5286 }
5287
5288 private static void logwtf(String s, Throwable t) {
5289 Log.wtf(TAG, s, t);
5290 }
5291
5292 private static void loge(String s) {
5293 Log.e(TAG, s);
5294 }
5295
5296 private static void loge(String s, Throwable t) {
5297 Log.e(TAG, s, t);
5298 }
5299
5300 /**
5301 * Return the information of all ongoing VPNs.
5302 *
5303 * <p>This method is used to update NetworkStatsService.
5304 *
5305 * <p>Must be called on the handler thread.
5306 */
5307 private UnderlyingNetworkInfo[] getAllVpnInfo() {
5308 ensureRunningOnConnectivityServiceThread();
5309 if (mLockdownEnabled) {
5310 return new UnderlyingNetworkInfo[0];
5311 }
5312 List<UnderlyingNetworkInfo> infoList = new ArrayList<>();
5313 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
5314 UnderlyingNetworkInfo info = createVpnInfo(nai);
5315 if (info != null) {
5316 infoList.add(info);
5317 }
5318 }
5319 return infoList.toArray(new UnderlyingNetworkInfo[infoList.size()]);
5320 }
5321
5322 /**
5323 * @return VPN information for accounting, or null if we can't retrieve all required
5324 * information, e.g underlying ifaces.
5325 */
5326 private UnderlyingNetworkInfo createVpnInfo(NetworkAgentInfo nai) {
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00005327 Network[] underlyingNetworks = nai.declaredUnderlyingNetworks;
5328 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
5329 // the underlyingNetworks list.
Lorenzo Colittibd079452021-07-02 11:47:57 +09005330 // TODO: stop using propagateUnderlyingCapabilities here, for example, by always
5331 // initializing NetworkAgentInfo#declaredUnderlyingNetworks to an empty array.
5332 if (underlyingNetworks == null && nai.propagateUnderlyingCapabilities()) {
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00005333 final NetworkAgentInfo defaultNai = getDefaultNetworkForUid(
5334 nai.networkCapabilities.getOwnerUid());
5335 if (defaultNai != null) {
5336 underlyingNetworks = new Network[] { defaultNai.network };
5337 }
5338 }
5339
5340 if (CollectionUtils.isEmpty(underlyingNetworks)) return null;
5341
5342 List<String> interfaces = new ArrayList<>();
5343 for (Network network : underlyingNetworks) {
5344 NetworkAgentInfo underlyingNai = getNetworkAgentInfoForNetwork(network);
5345 if (underlyingNai == null) continue;
5346 LinkProperties lp = underlyingNai.linkProperties;
5347 for (String iface : lp.getAllInterfaceNames()) {
5348 if (!TextUtils.isEmpty(iface)) {
5349 interfaces.add(iface);
5350 }
5351 }
5352 }
5353
5354 if (interfaces.isEmpty()) return null;
5355
5356 // Must be non-null or NetworkStatsService will crash.
5357 // Cannot happen in production code because Vpn only registers the NetworkAgent after the
5358 // tun or ipsec interface is created.
5359 // TODO: Remove this check.
5360 if (nai.linkProperties.getInterfaceName() == null) return null;
5361
5362 return new UnderlyingNetworkInfo(nai.networkCapabilities.getOwnerUid(),
5363 nai.linkProperties.getInterfaceName(), interfaces);
5364 }
5365
5366 // TODO This needs to be the default network that applies to the NAI.
5367 private Network[] underlyingNetworksOrDefault(final int ownerUid,
5368 Network[] underlyingNetworks) {
5369 final Network defaultNetwork = getNetwork(getDefaultNetworkForUid(ownerUid));
5370 if (underlyingNetworks == null && defaultNetwork != null) {
5371 // null underlying networks means to track the default.
5372 underlyingNetworks = new Network[] { defaultNetwork };
5373 }
5374 return underlyingNetworks;
5375 }
5376
5377 // Returns true iff |network| is an underlying network of |nai|.
5378 private boolean hasUnderlyingNetwork(NetworkAgentInfo nai, Network network) {
5379 // TODO: support more than one level of underlying networks, either via a fixed-depth search
5380 // (e.g., 2 levels of underlying networks), or via loop detection, or....
Lorenzo Colittibd079452021-07-02 11:47:57 +09005381 if (!nai.propagateUnderlyingCapabilities()) return false;
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00005382 final Network[] underlying = underlyingNetworksOrDefault(
5383 nai.networkCapabilities.getOwnerUid(), nai.declaredUnderlyingNetworks);
5384 return CollectionUtils.contains(underlying, network);
5385 }
5386
5387 /**
5388 * Recompute the capabilities for any networks that had a specific network as underlying.
5389 *
5390 * When underlying networks change, such networks may have to update capabilities to reflect
5391 * things like the metered bit, their transports, and so on. The capabilities are calculated
5392 * immediately. This method runs on the ConnectivityService thread.
5393 */
5394 private void propagateUnderlyingNetworkCapabilities(Network updatedNetwork) {
5395 ensureRunningOnConnectivityServiceThread();
5396 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
5397 if (updatedNetwork == null || hasUnderlyingNetwork(nai, updatedNetwork)) {
5398 updateCapabilitiesForNetwork(nai);
5399 }
5400 }
5401 }
5402
5403 private boolean isUidBlockedByVpn(int uid, List<UidRange> blockedUidRanges) {
5404 // Determine whether this UID is blocked because of always-on VPN lockdown. If a VPN applies
5405 // to the UID, then the UID is not blocked because always-on VPN lockdown applies only when
5406 // a VPN is not up.
5407 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
5408 if (vpnNai != null && !vpnNai.networkAgentConfig.allowBypass) return false;
5409 for (UidRange range : blockedUidRanges) {
5410 if (range.contains(uid)) return true;
5411 }
5412 return false;
5413 }
5414
5415 @Override
5416 public void setRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
5417 enforceNetworkStackOrSettingsPermission();
5418 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_REQUIRE_VPN_FOR_UIDS,
5419 encodeBool(requireVpn), 0 /* arg2 */, ranges));
5420 }
5421
5422 private void handleSetRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
5423 if (DBG) {
5424 Log.d(TAG, "Setting VPN " + (requireVpn ? "" : "not ") + "required for UIDs: "
5425 + Arrays.toString(ranges));
5426 }
5427 // Cannot use a Set since the list of UID ranges might contain duplicates.
5428 final List<UidRange> newVpnBlockedUidRanges = new ArrayList(mVpnBlockedUidRanges);
5429 for (int i = 0; i < ranges.length; i++) {
5430 if (requireVpn) {
5431 newVpnBlockedUidRanges.add(ranges[i]);
5432 } else {
5433 newVpnBlockedUidRanges.remove(ranges[i]);
5434 }
5435 }
5436
5437 try {
5438 mNetd.networkRejectNonSecureVpn(requireVpn, toUidRangeStableParcels(ranges));
5439 } catch (RemoteException | ServiceSpecificException e) {
5440 Log.e(TAG, "setRequireVpnForUids(" + requireVpn + ", "
5441 + Arrays.toString(ranges) + "): netd command failed: " + e);
5442 }
5443
5444 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
5445 final boolean curMetered = nai.networkCapabilities.isMetered();
5446 maybeNotifyNetworkBlocked(nai, curMetered, curMetered,
5447 mVpnBlockedUidRanges, newVpnBlockedUidRanges);
5448 }
5449
5450 mVpnBlockedUidRanges = newVpnBlockedUidRanges;
5451 }
5452
5453 @Override
5454 public void setLegacyLockdownVpnEnabled(boolean enabled) {
5455 enforceNetworkStackOrSettingsPermission();
5456 mHandler.post(() -> mLockdownEnabled = enabled);
5457 }
5458
5459 private boolean isLegacyLockdownNai(NetworkAgentInfo nai) {
5460 return mLockdownEnabled
5461 && getVpnType(nai) == VpnManager.TYPE_VPN_LEGACY
5462 && nai.networkCapabilities.appliesToUid(Process.FIRST_APPLICATION_UID);
5463 }
5464
5465 private NetworkAgentInfo getLegacyLockdownNai() {
5466 if (!mLockdownEnabled) {
5467 return null;
5468 }
5469 // The legacy lockdown VPN always only applies to userId 0.
5470 final NetworkAgentInfo nai = getVpnForUid(Process.FIRST_APPLICATION_UID);
5471 if (nai == null || !isLegacyLockdownNai(nai)) return null;
5472
5473 // The legacy lockdown VPN must always have exactly one underlying network.
5474 // This code may run on any thread and declaredUnderlyingNetworks may change, so store it in
5475 // a local variable. There is no need to make a copy because its contents cannot change.
5476 final Network[] underlying = nai.declaredUnderlyingNetworks;
5477 if (underlying == null || underlying.length != 1) {
5478 return null;
5479 }
5480
5481 // The legacy lockdown VPN always uses the default network.
5482 // If the VPN's underlying network is no longer the current default network, it means that
5483 // the default network has just switched, and the VPN is about to disconnect.
5484 // Report that the VPN is not connected, so the state of NetworkInfo objects overwritten
5485 // by filterForLegacyLockdown will be set to CONNECTING and not CONNECTED.
5486 final NetworkAgentInfo defaultNetwork = getDefaultNetwork();
5487 if (defaultNetwork == null || !defaultNetwork.network.equals(underlying[0])) {
5488 return null;
5489 }
5490
5491 return nai;
5492 };
5493
5494 // TODO: move all callers to filterForLegacyLockdown and delete this method.
5495 // This likely requires making sendLegacyNetworkBroadcast take a NetworkInfo object instead of
5496 // just a DetailedState object.
5497 private DetailedState getLegacyLockdownState(DetailedState origState) {
5498 if (origState != DetailedState.CONNECTED) {
5499 return origState;
5500 }
5501 return (mLockdownEnabled && getLegacyLockdownNai() == null)
5502 ? DetailedState.CONNECTING
5503 : DetailedState.CONNECTED;
5504 }
5505
5506 private void filterForLegacyLockdown(NetworkInfo ni) {
5507 if (!mLockdownEnabled || !ni.isConnected()) return;
5508 // The legacy lockdown VPN replaces the state of every network in CONNECTED state with the
5509 // state of its VPN. This is to ensure that when an underlying network connects, apps will
5510 // not see a CONNECTIVITY_ACTION broadcast for a network in state CONNECTED until the VPN
5511 // comes up, at which point there is a new CONNECTIVITY_ACTION broadcast for the underlying
5512 // network, this time with a state of CONNECTED.
5513 //
5514 // Now that the legacy lockdown code lives in ConnectivityService, and no longer has access
5515 // to the internal state of the Vpn object, always replace the state with CONNECTING. This
5516 // is not too far off the truth, since an always-on VPN, when not connected, is always
5517 // trying to reconnect.
5518 if (getLegacyLockdownNai() == null) {
5519 ni.setDetailedState(DetailedState.CONNECTING, "", null);
5520 }
5521 }
5522
5523 @Override
5524 public void setProvisioningNotificationVisible(boolean visible, int networkType,
5525 String action) {
5526 enforceSettingsPermission();
5527 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
5528 return;
5529 }
5530 final long ident = Binder.clearCallingIdentity();
5531 try {
5532 // Concatenate the range of types onto the range of NetIDs.
5533 int id = NetIdManager.MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
5534 mNotifier.setProvNotificationVisible(visible, id, action);
5535 } finally {
5536 Binder.restoreCallingIdentity(ident);
5537 }
5538 }
5539
5540 @Override
5541 public void setAirplaneMode(boolean enable) {
5542 enforceAirplaneModePermission();
5543 final long ident = Binder.clearCallingIdentity();
5544 try {
5545 final ContentResolver cr = mContext.getContentResolver();
5546 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
5547 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
5548 intent.putExtra("state", enable);
5549 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
5550 } finally {
5551 Binder.restoreCallingIdentity(ident);
5552 }
5553 }
5554
5555 private void onUserAdded(@NonNull final UserHandle user) {
5556 mPermissionMonitor.onUserAdded(user);
5557 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
5558 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
5559 }
5560 }
5561
5562 private void onUserRemoved(@NonNull final UserHandle user) {
5563 mPermissionMonitor.onUserRemoved(user);
5564 // If there was a network preference for this user, remove it.
5565 handleSetProfileNetworkPreference(new ProfileNetworkPreferences.Preference(user, null),
5566 null /* listener */);
5567 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
5568 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
5569 }
5570 }
5571
5572 private void onPackageChanged(@NonNull final String packageName) {
5573 // This is necessary in case a package is added or removed, but also when it's replaced to
5574 // run as a new UID by its manifest rules. Also, if a separate package shares the same UID
5575 // as one in the preferences, then it should follow the same routing as that other package,
5576 // which means updating the rules is never to be needed in this case (whether it joins or
5577 // leaves a UID with a preference).
5578 if (isMappedInOemNetworkPreference(packageName)) {
5579 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
5580 }
5581 }
5582
5583 private final BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
5584 @Override
5585 public void onReceive(Context context, Intent intent) {
5586 ensureRunningOnConnectivityServiceThread();
5587 final String action = intent.getAction();
5588 final UserHandle user = intent.getParcelableExtra(Intent.EXTRA_USER);
5589
5590 // User should be filled for below intents, check the existence.
5591 if (user == null) {
5592 Log.wtf(TAG, intent.getAction() + " broadcast without EXTRA_USER");
5593 return;
5594 }
5595
5596 if (Intent.ACTION_USER_ADDED.equals(action)) {
5597 onUserAdded(user);
5598 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
5599 onUserRemoved(user);
5600 } else {
5601 Log.wtf(TAG, "received unexpected intent: " + action);
5602 }
5603 }
5604 };
5605
5606 private final BroadcastReceiver mPackageIntentReceiver = new BroadcastReceiver() {
5607 @Override
5608 public void onReceive(Context context, Intent intent) {
5609 ensureRunningOnConnectivityServiceThread();
5610 switch (intent.getAction()) {
5611 case Intent.ACTION_PACKAGE_ADDED:
5612 case Intent.ACTION_PACKAGE_REMOVED:
5613 case Intent.ACTION_PACKAGE_REPLACED:
5614 onPackageChanged(intent.getData().getSchemeSpecificPart());
5615 break;
5616 default:
5617 Log.wtf(TAG, "received unexpected intent: " + intent.getAction());
5618 }
5619 }
5620 };
5621
5622 private final HashMap<Messenger, NetworkProviderInfo> mNetworkProviderInfos = new HashMap<>();
5623 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests = new HashMap<>();
5624
5625 private static class NetworkProviderInfo {
5626 public final String name;
5627 public final Messenger messenger;
5628 private final IBinder.DeathRecipient mDeathRecipient;
5629 public final int providerId;
5630
5631 NetworkProviderInfo(String name, Messenger messenger, int providerId,
5632 @NonNull IBinder.DeathRecipient deathRecipient) {
5633 this.name = name;
5634 this.messenger = messenger;
5635 this.providerId = providerId;
5636 mDeathRecipient = deathRecipient;
5637
5638 if (mDeathRecipient == null) {
5639 throw new AssertionError("Must pass a deathRecipient");
5640 }
5641 }
5642
5643 void connect(Context context, Handler handler) {
5644 try {
5645 messenger.getBinder().linkToDeath(mDeathRecipient, 0);
5646 } catch (RemoteException e) {
5647 mDeathRecipient.binderDied();
5648 }
5649 }
5650 }
5651
5652 private void ensureAllNetworkRequestsHaveType(List<NetworkRequest> requests) {
5653 for (int i = 0; i < requests.size(); i++) {
5654 ensureNetworkRequestHasType(requests.get(i));
5655 }
5656 }
5657
5658 private void ensureNetworkRequestHasType(NetworkRequest request) {
5659 if (request.type == NetworkRequest.Type.NONE) {
5660 throw new IllegalArgumentException(
5661 "All NetworkRequests in ConnectivityService must have a type");
5662 }
5663 }
5664
5665 /**
5666 * Tracks info about the requester.
5667 * Also used to notice when the calling process dies so as to self-expire
5668 */
5669 @VisibleForTesting
5670 protected class NetworkRequestInfo implements IBinder.DeathRecipient {
5671 // The requests to be satisfied in priority order. Non-multilayer requests will only have a
5672 // single NetworkRequest in mRequests.
5673 final List<NetworkRequest> mRequests;
5674
5675 // mSatisfier and mActiveRequest rely on one another therefore set them together.
5676 void setSatisfier(
5677 @Nullable final NetworkAgentInfo satisfier,
5678 @Nullable final NetworkRequest activeRequest) {
5679 mSatisfier = satisfier;
5680 mActiveRequest = activeRequest;
5681 }
5682
5683 // The network currently satisfying this NRI. Only one request in an NRI can have a
5684 // satisfier. For non-multilayer requests, only non-listen requests can have a satisfier.
5685 @Nullable
5686 private NetworkAgentInfo mSatisfier;
5687 NetworkAgentInfo getSatisfier() {
5688 return mSatisfier;
5689 }
5690
5691 // The request in mRequests assigned to a network agent. This is null if none of the
5692 // requests in mRequests can be satisfied. This member has the constraint of only being
5693 // accessible on the handler thread.
5694 @Nullable
5695 private NetworkRequest mActiveRequest;
5696 NetworkRequest getActiveRequest() {
5697 return mActiveRequest;
5698 }
5699
5700 final PendingIntent mPendingIntent;
5701 boolean mPendingIntentSent;
5702 @Nullable
5703 final Messenger mMessenger;
5704
5705 // Information about the caller that caused this object to be created.
5706 @Nullable
5707 private final IBinder mBinder;
5708 final int mPid;
5709 final int mUid;
5710 final @NetworkCallback.Flag int mCallbackFlags;
5711 @Nullable
5712 final String mCallingAttributionTag;
5713
5714 // Counter keeping track of this NRI.
5715 final PerUidCounter mPerUidCounter;
5716
5717 // Effective UID of this request. This is different from mUid when a privileged process
5718 // files a request on behalf of another UID. This UID is used to determine blocked status,
5719 // UID matching, and so on. mUid above is used for permission checks and to enforce the
5720 // maximum limit of registered callbacks per UID.
5721 final int mAsUid;
5722
paulhu48291862021-07-14 14:53:57 +08005723 // Preference order of this request.
5724 final int mPreferenceOrder;
paulhuc2198772021-05-26 15:19:20 +08005725
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00005726 // In order to preserve the mapping of NetworkRequest-to-callback when apps register
5727 // callbacks using a returned NetworkRequest, the original NetworkRequest needs to be
5728 // maintained for keying off of. This is only a concern when the original nri
5729 // mNetworkRequests changes which happens currently for apps that register callbacks to
5730 // track the default network. In those cases, the nri is updated to have mNetworkRequests
5731 // that match the per-app default nri that currently tracks the calling app's uid so that
5732 // callbacks are fired at the appropriate time. When the callbacks fire,
5733 // mNetworkRequestForCallback will be used so as to preserve the caller's mapping. When
5734 // callbacks are updated to key off of an nri vs NetworkRequest, this stops being an issue.
5735 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
5736 @NonNull
5737 private final NetworkRequest mNetworkRequestForCallback;
5738 NetworkRequest getNetworkRequestForCallback() {
5739 return mNetworkRequestForCallback;
5740 }
5741
5742 /**
5743 * Get the list of UIDs this nri applies to.
5744 */
5745 @NonNull
paulhu71ad4f12021-05-25 14:56:27 +08005746 Set<UidRange> getUids() {
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00005747 // networkCapabilities.getUids() returns a defensive copy.
5748 // multilayer requests will all have the same uids so return the first one.
5749 final Set<UidRange> uids = mRequests.get(0).networkCapabilities.getUidRanges();
5750 return (null == uids) ? new ArraySet<>() : uids;
5751 }
5752
5753 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r,
5754 @Nullable final PendingIntent pi, @Nullable String callingAttributionTag) {
paulhuc2198772021-05-26 15:19:20 +08005755 this(asUid, Collections.singletonList(r), r, pi, callingAttributionTag,
paulhu48291862021-07-14 14:53:57 +08005756 PREFERENCE_ORDER_INVALID);
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00005757 }
5758
5759 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
5760 @NonNull final NetworkRequest requestForCallback, @Nullable final PendingIntent pi,
paulhu48291862021-07-14 14:53:57 +08005761 @Nullable String callingAttributionTag, final int preferenceOrder) {
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00005762 ensureAllNetworkRequestsHaveType(r);
5763 mRequests = initializeRequests(r);
5764 mNetworkRequestForCallback = requestForCallback;
5765 mPendingIntent = pi;
5766 mMessenger = null;
5767 mBinder = null;
5768 mPid = getCallingPid();
5769 mUid = mDeps.getCallingUid();
5770 mAsUid = asUid;
5771 mPerUidCounter = getRequestCounter(this);
5772 mPerUidCounter.incrementCountOrThrow(mUid);
5773 /**
5774 * Location sensitive data not included in pending intent. Only included in
5775 * {@link NetworkCallback}.
5776 */
5777 mCallbackFlags = NetworkCallback.FLAG_NONE;
5778 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08005779 mPreferenceOrder = preferenceOrder;
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00005780 }
5781
5782 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r, @Nullable final Messenger m,
5783 @Nullable final IBinder binder,
5784 @NetworkCallback.Flag int callbackFlags,
5785 @Nullable String callingAttributionTag) {
5786 this(asUid, Collections.singletonList(r), r, m, binder, callbackFlags,
5787 callingAttributionTag);
5788 }
5789
5790 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
5791 @NonNull final NetworkRequest requestForCallback, @Nullable final Messenger m,
5792 @Nullable final IBinder binder,
5793 @NetworkCallback.Flag int callbackFlags,
5794 @Nullable String callingAttributionTag) {
5795 super();
5796 ensureAllNetworkRequestsHaveType(r);
5797 mRequests = initializeRequests(r);
5798 mNetworkRequestForCallback = requestForCallback;
5799 mMessenger = m;
5800 mBinder = binder;
5801 mPid = getCallingPid();
5802 mUid = mDeps.getCallingUid();
5803 mAsUid = asUid;
5804 mPendingIntent = null;
5805 mPerUidCounter = getRequestCounter(this);
5806 mPerUidCounter.incrementCountOrThrow(mUid);
5807 mCallbackFlags = callbackFlags;
5808 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08005809 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00005810 linkDeathRecipient();
5811 }
5812
5813 NetworkRequestInfo(@NonNull final NetworkRequestInfo nri,
5814 @NonNull final List<NetworkRequest> r) {
5815 super();
5816 ensureAllNetworkRequestsHaveType(r);
5817 mRequests = initializeRequests(r);
5818 mNetworkRequestForCallback = nri.getNetworkRequestForCallback();
5819 final NetworkAgentInfo satisfier = nri.getSatisfier();
5820 if (null != satisfier) {
5821 // If the old NRI was satisfied by an NAI, then it may have had an active request.
5822 // The active request is necessary to figure out what callbacks to send, in
5823 // particular then a network updates its capabilities.
5824 // As this code creates a new NRI with a new set of requests, figure out which of
5825 // the list of requests should be the active request. It is always the first
5826 // request of the list that can be satisfied by the satisfier since the order of
5827 // requests is a priority order.
5828 // Note even in the presence of a satisfier there may not be an active request,
5829 // when the satisfier is the no-service network.
5830 NetworkRequest activeRequest = null;
5831 for (final NetworkRequest candidate : r) {
5832 if (candidate.canBeSatisfiedBy(satisfier.networkCapabilities)) {
5833 activeRequest = candidate;
5834 break;
5835 }
5836 }
5837 setSatisfier(satisfier, activeRequest);
5838 }
5839 mMessenger = nri.mMessenger;
5840 mBinder = nri.mBinder;
5841 mPid = nri.mPid;
5842 mUid = nri.mUid;
5843 mAsUid = nri.mAsUid;
5844 mPendingIntent = nri.mPendingIntent;
5845 mPerUidCounter = getRequestCounter(this);
5846 mPerUidCounter.incrementCountOrThrow(mUid);
5847 mCallbackFlags = nri.mCallbackFlags;
5848 mCallingAttributionTag = nri.mCallingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08005849 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00005850 linkDeathRecipient();
5851 }
5852
5853 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r) {
paulhu48291862021-07-14 14:53:57 +08005854 this(asUid, Collections.singletonList(r), PREFERENCE_ORDER_INVALID);
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00005855 }
5856
paulhuc2198772021-05-26 15:19:20 +08005857 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
paulhu48291862021-07-14 14:53:57 +08005858 final int preferenceOrder) {
paulhuc2198772021-05-26 15:19:20 +08005859 this(asUid, r, r.get(0), null /* pi */, null /* callingAttributionTag */,
paulhu48291862021-07-14 14:53:57 +08005860 preferenceOrder);
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00005861 }
5862
5863 // True if this NRI is being satisfied. It also accounts for if the nri has its satisifer
5864 // set to the mNoServiceNetwork in which case mActiveRequest will be null thus returning
5865 // false.
5866 boolean isBeingSatisfied() {
5867 return (null != mSatisfier && null != mActiveRequest);
5868 }
5869
5870 boolean isMultilayerRequest() {
5871 return mRequests.size() > 1;
5872 }
5873
5874 private List<NetworkRequest> initializeRequests(List<NetworkRequest> r) {
5875 // Creating a defensive copy to prevent the sender from modifying the list being
5876 // reflected in the return value of this method.
5877 final List<NetworkRequest> tempRequests = new ArrayList<>(r);
5878 return Collections.unmodifiableList(tempRequests);
5879 }
5880
5881 void decrementRequestCount() {
5882 mPerUidCounter.decrementCount(mUid);
5883 }
5884
5885 void linkDeathRecipient() {
5886 if (null != mBinder) {
5887 try {
5888 mBinder.linkToDeath(this, 0);
5889 } catch (RemoteException e) {
5890 binderDied();
5891 }
5892 }
5893 }
5894
5895 void unlinkDeathRecipient() {
5896 if (null != mBinder) {
5897 mBinder.unlinkToDeath(this, 0);
5898 }
5899 }
5900
paulhu48291862021-07-14 14:53:57 +08005901 boolean hasHigherOrderThan(@NonNull final NetworkRequestInfo target) {
5902 // Compare two preference orders.
5903 return mPreferenceOrder < target.mPreferenceOrder;
paulhude5efb92021-05-26 21:56:03 +08005904 }
5905
paulhu48291862021-07-14 14:53:57 +08005906 int getPreferenceOrderForNetd() {
5907 if (mPreferenceOrder >= PREFERENCE_ORDER_NONE
5908 && mPreferenceOrder <= PREFERENCE_ORDER_LOWEST) {
5909 return mPreferenceOrder;
paulhude5efb92021-05-26 21:56:03 +08005910 }
paulhu48291862021-07-14 14:53:57 +08005911 return PREFERENCE_ORDER_NONE;
paulhude5efb92021-05-26 21:56:03 +08005912 }
5913
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00005914 @Override
5915 public void binderDied() {
5916 log("ConnectivityService NetworkRequestInfo binderDied(" +
James Mattis8f036802021-06-20 16:26:01 -07005917 "uid/pid:" + mUid + "/" + mPid + ", " + mBinder + ")");
Chalard Jean5bcc8382021-07-19 19:57:02 +09005918 // As an immutable collection, mRequests cannot change by the time the
5919 // lambda is evaluated on the handler thread so calling .get() from a binder thread
5920 // is acceptable. Use handleReleaseNetworkRequest and not directly
5921 // handleRemoveNetworkRequest so as to force a lookup in the requests map, in case
5922 // the app already unregistered the request.
5923 mHandler.post(() -> handleReleaseNetworkRequest(mRequests.get(0),
5924 mUid, false /* callOnUnavailable */));
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00005925 }
5926
5927 @Override
5928 public String toString() {
5929 final String asUidString = (mAsUid == mUid) ? "" : " asUid: " + mAsUid;
5930 return "uid/pid:" + mUid + "/" + mPid + asUidString + " activeRequest: "
5931 + (mActiveRequest == null ? null : mActiveRequest.requestId)
5932 + " callbackRequest: "
5933 + mNetworkRequestForCallback.requestId
5934 + " " + mRequests
5935 + (mPendingIntent == null ? "" : " to trigger " + mPendingIntent)
paulhude5efb92021-05-26 21:56:03 +08005936 + " callback flags: " + mCallbackFlags
paulhu48291862021-07-14 14:53:57 +08005937 + " order: " + mPreferenceOrder;
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00005938 }
5939 }
5940
5941 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
5942 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
5943 if (badCapability != null) {
5944 throw new IllegalArgumentException("Cannot request network with " + badCapability);
5945 }
5946 }
5947
5948 // This checks that the passed capabilities either do not request a
5949 // specific SSID/SignalStrength, or the calling app has permission to do so.
5950 private void ensureSufficientPermissionsForRequest(NetworkCapabilities nc,
5951 int callerPid, int callerUid, String callerPackageName) {
5952 if (null != nc.getSsid() && !checkSettingsPermission(callerPid, callerUid)) {
5953 throw new SecurityException("Insufficient permissions to request a specific SSID");
5954 }
5955
5956 if (nc.hasSignalStrength()
5957 && !checkNetworkSignalStrengthWakeupPermission(callerPid, callerUid)) {
5958 throw new SecurityException(
5959 "Insufficient permissions to request a specific signal strength");
5960 }
5961 mAppOpsManager.checkPackage(callerUid, callerPackageName);
5962
5963 if (!nc.getSubscriptionIds().isEmpty()) {
5964 enforceNetworkFactoryPermission();
5965 }
5966 }
5967
5968 private int[] getSignalStrengthThresholds(@NonNull final NetworkAgentInfo nai) {
5969 final SortedSet<Integer> thresholds = new TreeSet<>();
5970 synchronized (nai) {
5971 // mNetworkRequests may contain the same value multiple times in case of
5972 // multilayer requests. It won't matter in this case because the thresholds
5973 // will then be the same and be deduplicated as they enter the `thresholds` set.
5974 // TODO : have mNetworkRequests be a Set<NetworkRequestInfo> or the like.
5975 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
5976 for (final NetworkRequest req : nri.mRequests) {
5977 if (req.networkCapabilities.hasSignalStrength()
5978 && nai.satisfiesImmutableCapabilitiesOf(req)) {
5979 thresholds.add(req.networkCapabilities.getSignalStrength());
5980 }
5981 }
5982 }
5983 }
5984 return CollectionUtils.toIntArray(new ArrayList<>(thresholds));
5985 }
5986
5987 private void updateSignalStrengthThresholds(
5988 NetworkAgentInfo nai, String reason, NetworkRequest request) {
5989 final int[] thresholdsArray = getSignalStrengthThresholds(nai);
5990
5991 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
5992 String detail;
5993 if (request != null && request.networkCapabilities.hasSignalStrength()) {
5994 detail = reason + " " + request.networkCapabilities.getSignalStrength();
5995 } else {
5996 detail = reason;
5997 }
5998 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
5999 detail, Arrays.toString(thresholdsArray), nai.toShortString()));
6000 }
6001
6002 nai.onSignalStrengthThresholdsUpdated(thresholdsArray);
6003 }
6004
6005 private void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
6006 if (nc == null) {
6007 return;
6008 }
6009 NetworkSpecifier ns = nc.getNetworkSpecifier();
6010 if (ns == null) {
6011 return;
6012 }
6013 if (ns instanceof MatchAllNetworkSpecifier) {
6014 throw new IllegalArgumentException("A MatchAllNetworkSpecifier is not permitted");
6015 }
6016 }
6017
6018 private void ensureValid(NetworkCapabilities nc) {
6019 ensureValidNetworkSpecifier(nc);
6020 if (nc.isPrivateDnsBroken()) {
6021 throw new IllegalArgumentException("Can't request broken private DNS");
6022 }
6023 }
6024
6025 private boolean isTargetSdkAtleast(int version, int callingUid,
6026 @NonNull String callingPackageName) {
6027 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
6028 final PackageManager pm =
6029 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
6030 try {
6031 final int callingVersion = pm.getTargetSdkVersion(callingPackageName);
6032 if (callingVersion < version) return false;
6033 } catch (PackageManager.NameNotFoundException e) { }
6034 return true;
6035 }
6036
6037 @Override
6038 public NetworkRequest requestNetwork(int asUid, NetworkCapabilities networkCapabilities,
6039 int reqTypeInt, Messenger messenger, int timeoutMs, IBinder binder,
6040 int legacyType, int callbackFlags, @NonNull String callingPackageName,
6041 @Nullable String callingAttributionTag) {
6042 if (legacyType != TYPE_NONE && !checkNetworkStackPermission()) {
6043 if (isTargetSdkAtleast(Build.VERSION_CODES.M, mDeps.getCallingUid(),
6044 callingPackageName)) {
6045 throw new SecurityException("Insufficient permissions to specify legacy type");
6046 }
6047 }
6048 final NetworkCapabilities defaultNc = mDefaultRequest.mRequests.get(0).networkCapabilities;
6049 final int callingUid = mDeps.getCallingUid();
6050 // Privileged callers can track the default network of another UID by passing in a UID.
6051 if (asUid != Process.INVALID_UID) {
6052 enforceSettingsPermission();
6053 } else {
6054 asUid = callingUid;
6055 }
6056 final NetworkRequest.Type reqType;
6057 try {
6058 reqType = NetworkRequest.Type.values()[reqTypeInt];
6059 } catch (ArrayIndexOutOfBoundsException e) {
6060 throw new IllegalArgumentException("Unsupported request type " + reqTypeInt);
6061 }
6062 switch (reqType) {
6063 case TRACK_DEFAULT:
6064 // If the request type is TRACK_DEFAULT, the passed {@code networkCapabilities}
6065 // is unused and will be replaced by ones appropriate for the UID (usually, the
6066 // calling app). This allows callers to keep track of the default network.
6067 networkCapabilities = copyDefaultNetworkCapabilitiesForUid(
6068 defaultNc, asUid, callingUid, callingPackageName);
6069 enforceAccessPermission();
6070 break;
6071 case TRACK_SYSTEM_DEFAULT:
6072 enforceSettingsPermission();
6073 networkCapabilities = new NetworkCapabilities(defaultNc);
6074 break;
6075 case BACKGROUND_REQUEST:
6076 enforceNetworkStackOrSettingsPermission();
6077 // Fall-through since other checks are the same with normal requests.
6078 case REQUEST:
6079 networkCapabilities = new NetworkCapabilities(networkCapabilities);
6080 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
6081 callingAttributionTag);
6082 // TODO: this is incorrect. We mark the request as metered or not depending on
6083 // the state of the app when the request is filed, but we never change the
6084 // request if the app changes network state. http://b/29964605
6085 enforceMeteredApnPolicy(networkCapabilities);
6086 break;
6087 case LISTEN_FOR_BEST:
6088 enforceAccessPermission();
6089 networkCapabilities = new NetworkCapabilities(networkCapabilities);
6090 break;
6091 default:
6092 throw new IllegalArgumentException("Unsupported request type " + reqType);
6093 }
6094 ensureRequestableCapabilities(networkCapabilities);
6095 ensureSufficientPermissionsForRequest(networkCapabilities,
6096 Binder.getCallingPid(), callingUid, callingPackageName);
6097
6098 // Enforce FOREGROUND if the caller does not have permission to use background network.
6099 if (reqType == LISTEN_FOR_BEST) {
6100 restrictBackgroundRequestForCaller(networkCapabilities);
6101 }
6102
6103 // Set the UID range for this request to the single UID of the requester, unless the
6104 // requester has the permission to specify other UIDs.
6105 // This will overwrite any allowed UIDs in the requested capabilities. Though there
6106 // are no visible methods to set the UIDs, an app could use reflection to try and get
6107 // networks for other apps so it's essential that the UIDs are overwritten.
6108 // Also set the requester UID and package name in the request.
6109 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
6110 callingUid, callingPackageName);
6111
6112 if (timeoutMs < 0) {
6113 throw new IllegalArgumentException("Bad timeout specified");
6114 }
6115 ensureValid(networkCapabilities);
6116
6117 final NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
6118 nextNetworkRequestId(), reqType);
6119 final NetworkRequestInfo nri = getNriToRegister(
6120 asUid, networkRequest, messenger, binder, callbackFlags,
6121 callingAttributionTag);
6122 if (DBG) log("requestNetwork for " + nri);
6123
6124 // For TRACK_SYSTEM_DEFAULT callbacks, the capabilities have been modified since they were
6125 // copied from the default request above. (This is necessary to ensure, for example, that
6126 // the callback does not leak sensitive information to unprivileged apps.) Check that the
6127 // changes don't alter request matching.
6128 if (reqType == NetworkRequest.Type.TRACK_SYSTEM_DEFAULT &&
6129 (!networkCapabilities.equalRequestableCapabilities(defaultNc))) {
6130 throw new IllegalStateException(
6131 "TRACK_SYSTEM_DEFAULT capabilities don't match default request: "
6132 + networkCapabilities + " vs. " + defaultNc);
6133 }
6134
6135 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
6136 if (timeoutMs > 0) {
6137 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
6138 nri), timeoutMs);
6139 }
6140 return networkRequest;
6141 }
6142
6143 /**
6144 * Return the nri to be used when registering a network request. Specifically, this is used with
6145 * requests registered to track the default request. If there is currently a per-app default
6146 * tracking the app requestor, then we need to create a version of this nri that mirrors that of
6147 * the tracking per-app default so that callbacks are sent to the app requestor appropriately.
6148 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
6149 * when a privileged caller is tracking the default network for another uid.
6150 * @param nr the network request for the nri.
6151 * @param msgr the messenger for the nri.
6152 * @param binder the binder for the nri.
6153 * @param callingAttributionTag the calling attribution tag for the nri.
6154 * @return the nri to register.
6155 */
6156 private NetworkRequestInfo getNriToRegister(final int asUid, @NonNull final NetworkRequest nr,
6157 @Nullable final Messenger msgr, @Nullable final IBinder binder,
6158 @NetworkCallback.Flag int callbackFlags,
6159 @Nullable String callingAttributionTag) {
6160 final List<NetworkRequest> requests;
6161 if (NetworkRequest.Type.TRACK_DEFAULT == nr.type) {
6162 requests = copyDefaultNetworkRequestsForUid(
6163 asUid, nr.getRequestorUid(), nr.getRequestorPackageName());
6164 } else {
6165 requests = Collections.singletonList(nr);
6166 }
6167 return new NetworkRequestInfo(
6168 asUid, requests, nr, msgr, binder, callbackFlags, callingAttributionTag);
6169 }
6170
6171 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities,
6172 String callingPackageName, String callingAttributionTag) {
6173 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
6174 enforceConnectivityRestrictedNetworksPermission();
6175 } else {
6176 enforceChangePermission(callingPackageName, callingAttributionTag);
6177 }
6178 }
6179
6180 @Override
6181 public boolean requestBandwidthUpdate(Network network) {
6182 enforceAccessPermission();
6183 NetworkAgentInfo nai = null;
6184 if (network == null) {
6185 return false;
6186 }
6187 synchronized (mNetworkForNetId) {
6188 nai = mNetworkForNetId.get(network.getNetId());
6189 }
6190 if (nai != null) {
6191 nai.onBandwidthUpdateRequested();
6192 synchronized (mBandwidthRequests) {
6193 final int uid = mDeps.getCallingUid();
6194 Integer uidReqs = mBandwidthRequests.get(uid);
6195 if (uidReqs == null) {
6196 uidReqs = 0;
6197 }
6198 mBandwidthRequests.put(uid, ++uidReqs);
6199 }
6200 return true;
6201 }
6202 return false;
6203 }
6204
6205 private boolean isSystem(int uid) {
6206 return uid < Process.FIRST_APPLICATION_UID;
6207 }
6208
6209 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
6210 final int uid = mDeps.getCallingUid();
6211 if (isSystem(uid)) {
6212 // Exemption for system uid.
6213 return;
6214 }
6215 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
6216 // Policy already enforced.
6217 return;
6218 }
6219 final long ident = Binder.clearCallingIdentity();
6220 try {
6221 if (mPolicyManager.isUidRestrictedOnMeteredNetworks(uid)) {
6222 // If UID is restricted, don't allow them to bring up metered APNs.
6223 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
6224 }
6225 } finally {
6226 Binder.restoreCallingIdentity(ident);
6227 }
6228 }
6229
6230 @Override
6231 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
6232 PendingIntent operation, @NonNull String callingPackageName,
6233 @Nullable String callingAttributionTag) {
6234 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
6235 final int callingUid = mDeps.getCallingUid();
6236 networkCapabilities = new NetworkCapabilities(networkCapabilities);
6237 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
6238 callingAttributionTag);
6239 enforceMeteredApnPolicy(networkCapabilities);
6240 ensureRequestableCapabilities(networkCapabilities);
6241 ensureSufficientPermissionsForRequest(networkCapabilities,
6242 Binder.getCallingPid(), callingUid, callingPackageName);
6243 ensureValidNetworkSpecifier(networkCapabilities);
6244 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
6245 callingUid, callingPackageName);
6246
6247 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
6248 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
6249 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
6250 callingAttributionTag);
6251 if (DBG) log("pendingRequest for " + nri);
6252 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
6253 nri));
6254 return networkRequest;
6255 }
6256
6257 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
6258 mHandler.sendMessageDelayed(
6259 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
6260 mDeps.getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
6261 }
6262
6263 @Override
6264 public void releasePendingNetworkRequest(PendingIntent operation) {
6265 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
6266 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
6267 mDeps.getCallingUid(), 0, operation));
6268 }
6269
6270 // In order to implement the compatibility measure for pre-M apps that call
6271 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
6272 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
6273 // This ensures it has permission to do so.
6274 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
6275 if (nc == null) {
6276 return false;
6277 }
6278 int[] transportTypes = nc.getTransportTypes();
6279 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
6280 return false;
6281 }
6282 try {
6283 mContext.enforceCallingOrSelfPermission(
6284 android.Manifest.permission.ACCESS_WIFI_STATE,
6285 "ConnectivityService");
6286 } catch (SecurityException e) {
6287 return false;
6288 }
6289 return true;
6290 }
6291
6292 @Override
6293 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
6294 Messenger messenger, IBinder binder,
6295 @NetworkCallback.Flag int callbackFlags,
6296 @NonNull String callingPackageName, @NonNull String callingAttributionTag) {
6297 final int callingUid = mDeps.getCallingUid();
6298 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
6299 enforceAccessPermission();
6300 }
6301
6302 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
6303 ensureSufficientPermissionsForRequest(networkCapabilities,
6304 Binder.getCallingPid(), callingUid, callingPackageName);
6305 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
6306 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
6307 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
6308 // onLost and onAvailable callbacks when networks move in and out of the background.
6309 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
6310 // can't request networks.
6311 restrictBackgroundRequestForCaller(nc);
6312 ensureValid(nc);
6313
6314 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
6315 NetworkRequest.Type.LISTEN);
6316 NetworkRequestInfo nri =
6317 new NetworkRequestInfo(callingUid, networkRequest, messenger, binder, callbackFlags,
6318 callingAttributionTag);
6319 if (VDBG) log("listenForNetwork for " + nri);
6320
6321 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
6322 return networkRequest;
6323 }
6324
6325 @Override
6326 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
6327 PendingIntent operation, @NonNull String callingPackageName,
6328 @Nullable String callingAttributionTag) {
6329 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
6330 final int callingUid = mDeps.getCallingUid();
6331 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
6332 enforceAccessPermission();
6333 }
6334 ensureValid(networkCapabilities);
6335 ensureSufficientPermissionsForRequest(networkCapabilities,
6336 Binder.getCallingPid(), callingUid, callingPackageName);
6337 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
6338 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
6339
6340 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
6341 NetworkRequest.Type.LISTEN);
6342 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
6343 callingAttributionTag);
6344 if (VDBG) log("pendingListenForNetwork for " + nri);
6345
WeiZhang1cc3f172021-06-03 19:02:04 -05006346 mHandler.sendMessage(mHandler.obtainMessage(
6347 EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT, nri));
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00006348 }
6349
6350 /** Returns the next Network provider ID. */
6351 public final int nextNetworkProviderId() {
6352 return mNextNetworkProviderId.getAndIncrement();
6353 }
6354
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00006355 @Override
6356 public void releaseNetworkRequest(NetworkRequest networkRequest) {
6357 ensureNetworkRequestHasType(networkRequest);
6358 mHandler.sendMessage(mHandler.obtainMessage(
6359 EVENT_RELEASE_NETWORK_REQUEST, mDeps.getCallingUid(), 0, networkRequest));
6360 }
6361
6362 private void handleRegisterNetworkProvider(NetworkProviderInfo npi) {
6363 if (mNetworkProviderInfos.containsKey(npi.messenger)) {
6364 // Avoid creating duplicates. even if an app makes a direct AIDL call.
6365 // This will never happen if an app calls ConnectivityManager#registerNetworkProvider,
6366 // as that will throw if a duplicate provider is registered.
6367 loge("Attempt to register existing NetworkProviderInfo "
6368 + mNetworkProviderInfos.get(npi.messenger).name);
6369 return;
6370 }
6371
6372 if (DBG) log("Got NetworkProvider Messenger for " + npi.name);
6373 mNetworkProviderInfos.put(npi.messenger, npi);
6374 npi.connect(mContext, mTrackerHandler);
6375 }
6376
6377 @Override
6378 public int registerNetworkProvider(Messenger messenger, String name) {
6379 enforceNetworkFactoryOrSettingsPermission();
6380 Objects.requireNonNull(messenger, "messenger must be non-null");
6381 NetworkProviderInfo npi = new NetworkProviderInfo(name, messenger,
6382 nextNetworkProviderId(), () -> unregisterNetworkProvider(messenger));
6383 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_PROVIDER, npi));
6384 return npi.providerId;
6385 }
6386
6387 @Override
6388 public void unregisterNetworkProvider(Messenger messenger) {
6389 enforceNetworkFactoryOrSettingsPermission();
6390 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_PROVIDER, messenger));
6391 }
6392
6393 @Override
6394 public void offerNetwork(final int providerId,
6395 @NonNull final NetworkScore score, @NonNull final NetworkCapabilities caps,
6396 @NonNull final INetworkOfferCallback callback) {
6397 Objects.requireNonNull(score);
6398 Objects.requireNonNull(caps);
6399 Objects.requireNonNull(callback);
6400 final NetworkOffer offer = new NetworkOffer(
6401 FullScore.makeProspectiveScore(score, caps), caps, callback, providerId);
6402 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_OFFER, offer));
6403 }
6404
6405 @Override
6406 public void unofferNetwork(@NonNull final INetworkOfferCallback callback) {
6407 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_OFFER, callback));
6408 }
6409
6410 private void handleUnregisterNetworkProvider(Messenger messenger) {
6411 NetworkProviderInfo npi = mNetworkProviderInfos.remove(messenger);
6412 if (npi == null) {
6413 loge("Failed to find Messenger in unregisterNetworkProvider");
6414 return;
6415 }
6416 // Unregister all the offers from this provider
6417 final ArrayList<NetworkOfferInfo> toRemove = new ArrayList<>();
6418 for (final NetworkOfferInfo noi : mNetworkOffers) {
6419 if (noi.offer.providerId == npi.providerId) {
6420 // Can't call handleUnregisterNetworkOffer here because iteration is in progress
6421 toRemove.add(noi);
6422 }
6423 }
6424 for (final NetworkOfferInfo noi : toRemove) {
6425 handleUnregisterNetworkOffer(noi);
6426 }
6427 if (DBG) log("unregisterNetworkProvider for " + npi.name);
6428 }
6429
6430 @Override
6431 public void declareNetworkRequestUnfulfillable(@NonNull final NetworkRequest request) {
6432 if (request.hasTransport(TRANSPORT_TEST)) {
6433 enforceNetworkFactoryOrTestNetworksPermission();
6434 } else {
6435 enforceNetworkFactoryPermission();
6436 }
6437 final NetworkRequestInfo nri = mNetworkRequests.get(request);
6438 if (nri != null) {
6439 // declareNetworkRequestUnfulfillable() paths don't apply to multilayer requests.
6440 ensureNotMultilayerRequest(nri, "declareNetworkRequestUnfulfillable");
6441 mHandler.post(() -> handleReleaseNetworkRequest(
6442 nri.mRequests.get(0), mDeps.getCallingUid(), true));
6443 }
6444 }
6445
6446 // NOTE: Accessed on multiple threads, must be synchronized on itself.
6447 @GuardedBy("mNetworkForNetId")
6448 private final SparseArray<NetworkAgentInfo> mNetworkForNetId = new SparseArray<>();
6449 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
6450 // An entry is first reserved with NetIdManager, prior to being added to mNetworkForNetId, so
6451 // there may not be a strict 1:1 correlation between the two.
6452 private final NetIdManager mNetIdManager;
6453
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09006454 // Tracks all NetworkAgents that are currently registered.
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00006455 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
6456 private final ArraySet<NetworkAgentInfo> mNetworkAgentInfos = new ArraySet<>();
6457
6458 // UID ranges for users that are currently blocked by VPNs.
6459 // This array is accessed and iterated on multiple threads without holding locks, so its
6460 // contents must never be mutated. When the ranges change, the array is replaced with a new one
6461 // (on the handler thread).
6462 private volatile List<UidRange> mVpnBlockedUidRanges = new ArrayList<>();
6463
6464 // Must only be accessed on the handler thread
6465 @NonNull
6466 private final ArrayList<NetworkOfferInfo> mNetworkOffers = new ArrayList<>();
6467
6468 @GuardedBy("mBlockedAppUids")
6469 private final HashSet<Integer> mBlockedAppUids = new HashSet<>();
6470
6471 // Current OEM network preferences. This object must only be written to on the handler thread.
6472 // Since it is immutable and always non-null, other threads may read it if they only care
6473 // about seeing a consistent object but not that it is current.
6474 @NonNull
6475 private OemNetworkPreferences mOemNetworkPreferences =
6476 new OemNetworkPreferences.Builder().build();
6477 // Current per-profile network preferences. This object follows the same threading rules as
6478 // the OEM network preferences above.
6479 @NonNull
6480 private ProfileNetworkPreferences mProfileNetworkPreferences = new ProfileNetworkPreferences();
6481
paulhu71ad4f12021-05-25 14:56:27 +08006482 // A set of UIDs that should use mobile data preferentially if available. This object follows
6483 // the same threading rules as the OEM network preferences above.
6484 @NonNull
6485 private Set<Integer> mMobileDataPreferredUids = new ArraySet<>();
6486
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00006487 // OemNetworkPreferences activity String log entries.
6488 private static final int MAX_OEM_NETWORK_PREFERENCE_LOGS = 20;
6489 @NonNull
6490 private final LocalLog mOemNetworkPreferencesLogs =
6491 new LocalLog(MAX_OEM_NETWORK_PREFERENCE_LOGS);
6492
6493 /**
6494 * Determine whether a given package has a mapping in the current OemNetworkPreferences.
6495 * @param packageName the package name to check existence of a mapping for.
6496 * @return true if a mapping exists, false otherwise
6497 */
6498 private boolean isMappedInOemNetworkPreference(@NonNull final String packageName) {
6499 return mOemNetworkPreferences.getNetworkPreferences().containsKey(packageName);
6500 }
6501
6502 // The always-on request for an Internet-capable network that apps without a specific default
6503 // fall back to.
6504 @VisibleForTesting
6505 @NonNull
6506 final NetworkRequestInfo mDefaultRequest;
6507 // Collection of NetworkRequestInfo's used for default networks.
6508 @VisibleForTesting
6509 @NonNull
6510 final ArraySet<NetworkRequestInfo> mDefaultNetworkRequests = new ArraySet<>();
6511
6512 private boolean isPerAppDefaultRequest(@NonNull final NetworkRequestInfo nri) {
6513 return (mDefaultNetworkRequests.contains(nri) && mDefaultRequest != nri);
6514 }
6515
6516 /**
6517 * Return the default network request currently tracking the given uid.
6518 * @param uid the uid to check.
6519 * @return the NetworkRequestInfo tracking the given uid.
6520 */
6521 @NonNull
6522 private NetworkRequestInfo getDefaultRequestTrackingUid(final int uid) {
paulhude5efb92021-05-26 21:56:03 +08006523 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00006524 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00006525 // Checking the first request is sufficient as only multilayer requests will have more
6526 // than one request and for multilayer, all requests will track the same uids.
6527 if (nri.mRequests.get(0).networkCapabilities.appliesToUid(uid)) {
paulhude5efb92021-05-26 21:56:03 +08006528 // Find out the highest priority request.
paulhu48291862021-07-14 14:53:57 +08006529 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhude5efb92021-05-26 21:56:03 +08006530 highestPriorityNri = nri;
6531 }
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00006532 }
6533 }
paulhude5efb92021-05-26 21:56:03 +08006534 return highestPriorityNri;
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00006535 }
6536
6537 /**
6538 * Get a copy of the network requests of the default request that is currently tracking the
6539 * given uid.
6540 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
6541 * when a privileged caller is tracking the default network for another uid.
6542 * @param requestorUid the uid to check the default for.
6543 * @param requestorPackageName the requestor's package name.
6544 * @return a copy of the default's NetworkRequest that is tracking the given uid.
6545 */
6546 @NonNull
6547 private List<NetworkRequest> copyDefaultNetworkRequestsForUid(
6548 final int asUid, final int requestorUid, @NonNull final String requestorPackageName) {
6549 return copyNetworkRequestsForUid(
6550 getDefaultRequestTrackingUid(asUid).mRequests,
6551 asUid, requestorUid, requestorPackageName);
6552 }
6553
6554 /**
6555 * Copy the given nri's NetworkRequest collection.
6556 * @param requestsToCopy the NetworkRequest collection to be copied.
6557 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
6558 * when a privileged caller is tracking the default network for another uid.
6559 * @param requestorUid the uid to set on the copied collection.
6560 * @param requestorPackageName the package name to set on the copied collection.
6561 * @return the copied NetworkRequest collection.
6562 */
6563 @NonNull
6564 private List<NetworkRequest> copyNetworkRequestsForUid(
6565 @NonNull final List<NetworkRequest> requestsToCopy, final int asUid,
6566 final int requestorUid, @NonNull final String requestorPackageName) {
6567 final List<NetworkRequest> requests = new ArrayList<>();
6568 for (final NetworkRequest nr : requestsToCopy) {
6569 requests.add(new NetworkRequest(copyDefaultNetworkCapabilitiesForUid(
6570 nr.networkCapabilities, asUid, requestorUid, requestorPackageName),
6571 nr.legacyType, nextNetworkRequestId(), nr.type));
6572 }
6573 return requests;
6574 }
6575
6576 @NonNull
6577 private NetworkCapabilities copyDefaultNetworkCapabilitiesForUid(
6578 @NonNull final NetworkCapabilities netCapToCopy, final int asUid,
6579 final int requestorUid, @NonNull final String requestorPackageName) {
6580 // These capabilities are for a TRACK_DEFAULT callback, so:
6581 // 1. Remove NET_CAPABILITY_VPN, because it's (currently!) the only difference between
6582 // mDefaultRequest and a per-UID default request.
6583 // TODO: stop depending on the fact that these two unrelated things happen to be the same
6584 // 2. Always set the UIDs to asUid. restrictRequestUidsForCallerAndSetRequestorInfo will
6585 // not do this in the case of a privileged application.
6586 final NetworkCapabilities netCap = new NetworkCapabilities(netCapToCopy);
6587 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
6588 netCap.setSingleUid(asUid);
6589 restrictRequestUidsForCallerAndSetRequestorInfo(
6590 netCap, requestorUid, requestorPackageName);
6591 return netCap;
6592 }
6593
6594 /**
6595 * Get the nri that is currently being tracked for callbacks by per-app defaults.
6596 * @param nr the network request to check for equality against.
6597 * @return the nri if one exists, null otherwise.
6598 */
6599 @Nullable
6600 private NetworkRequestInfo getNriForAppRequest(@NonNull final NetworkRequest nr) {
6601 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
6602 if (nri.getNetworkRequestForCallback().equals(nr)) {
6603 return nri;
6604 }
6605 }
6606 return null;
6607 }
6608
6609 /**
6610 * Check if an nri is currently being managed by per-app default networking.
6611 * @param nri the nri to check.
6612 * @return true if this nri is currently being managed by per-app default networking.
6613 */
6614 private boolean isPerAppTrackedNri(@NonNull final NetworkRequestInfo nri) {
6615 // nri.mRequests.get(0) is only different from the original request filed in
6616 // nri.getNetworkRequestForCallback() if nri.mRequests was changed by per-app default
6617 // functionality therefore if these two don't match, it means this particular nri is
6618 // currently being managed by a per-app default.
6619 return nri.getNetworkRequestForCallback() != nri.mRequests.get(0);
6620 }
6621
6622 /**
6623 * Determine if an nri is a managed default request that disallows default networking.
6624 * @param nri the request to evaluate
6625 * @return true if device-default networking is disallowed
6626 */
6627 private boolean isDefaultBlocked(@NonNull final NetworkRequestInfo nri) {
6628 // Check if this nri is a managed default that supports the default network at its
6629 // lowest priority request.
6630 final NetworkRequest defaultNetworkRequest = mDefaultRequest.mRequests.get(0);
6631 final NetworkCapabilities lowestPriorityNetCap =
6632 nri.mRequests.get(nri.mRequests.size() - 1).networkCapabilities;
6633 return isPerAppDefaultRequest(nri)
6634 && !(defaultNetworkRequest.networkCapabilities.equalRequestableCapabilities(
6635 lowestPriorityNetCap));
6636 }
6637
6638 // Request used to optionally keep mobile data active even when higher
6639 // priority networks like Wi-Fi are active.
6640 private final NetworkRequest mDefaultMobileDataRequest;
6641
6642 // Request used to optionally keep wifi data active even when higher
6643 // priority networks like ethernet are active.
6644 private final NetworkRequest mDefaultWifiRequest;
6645
6646 // Request used to optionally keep vehicle internal network always active
6647 private final NetworkRequest mDefaultVehicleRequest;
6648
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00006649 // Sentinel NAI used to direct apps with default networks that should have no connectivity to a
6650 // network with no service. This NAI should never be matched against, nor should any public API
6651 // ever return the associated network. For this reason, this NAI is not in the list of available
6652 // NAIs. It is used in computeNetworkReassignment() to be set as the satisfier for non-device
6653 // default requests that don't support using the device default network which will ultimately
6654 // allow ConnectivityService to use this no-service network when calling makeDefaultForApps().
6655 @VisibleForTesting
6656 final NetworkAgentInfo mNoServiceNetwork;
6657
6658 // The NetworkAgentInfo currently satisfying the default request, if any.
6659 private NetworkAgentInfo getDefaultNetwork() {
6660 return mDefaultRequest.mSatisfier;
6661 }
6662
6663 private NetworkAgentInfo getDefaultNetworkForUid(final int uid) {
paulhude5efb92021-05-26 21:56:03 +08006664 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00006665 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
6666 // Currently, all network requests will have the same uids therefore checking the first
6667 // one is sufficient. If/when uids are tracked at the nri level, this can change.
6668 final Set<UidRange> uids = nri.mRequests.get(0).networkCapabilities.getUidRanges();
6669 if (null == uids) {
6670 continue;
6671 }
6672 for (final UidRange range : uids) {
6673 if (range.contains(uid)) {
paulhu48291862021-07-14 14:53:57 +08006674 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhude5efb92021-05-26 21:56:03 +08006675 highestPriorityNri = nri;
6676 }
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00006677 }
6678 }
6679 }
paulhude5efb92021-05-26 21:56:03 +08006680 return highestPriorityNri.getSatisfier();
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00006681 }
6682
6683 @Nullable
6684 private Network getNetwork(@Nullable NetworkAgentInfo nai) {
6685 return nai != null ? nai.network : null;
6686 }
6687
6688 private void ensureRunningOnConnectivityServiceThread() {
6689 if (mHandler.getLooper().getThread() != Thread.currentThread()) {
6690 throw new IllegalStateException(
6691 "Not running on ConnectivityService thread: "
6692 + Thread.currentThread().getName());
6693 }
6694 }
6695
6696 @VisibleForTesting
6697 protected boolean isDefaultNetwork(NetworkAgentInfo nai) {
6698 return nai == getDefaultNetwork();
6699 }
6700
6701 /**
6702 * Register a new agent with ConnectivityService to handle a network.
6703 *
6704 * @param na a reference for ConnectivityService to contact the agent asynchronously.
6705 * @param networkInfo the initial info associated with this network. It can be updated later :
6706 * see {@link #updateNetworkInfo}.
6707 * @param linkProperties the initial link properties of this network. They can be updated
6708 * later : see {@link #updateLinkProperties}.
6709 * @param networkCapabilities the initial capabilites of this network. They can be updated
6710 * later : see {@link #updateCapabilities}.
6711 * @param initialScore the initial score of the network. See
6712 * {@link NetworkAgentInfo#getCurrentScore}.
6713 * @param networkAgentConfig metadata about the network. This is never updated.
6714 * @param providerId the ID of the provider owning this NetworkAgent.
6715 * @return the network created for this agent.
6716 */
6717 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo networkInfo,
6718 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
6719 @NonNull NetworkScore initialScore, NetworkAgentConfig networkAgentConfig,
6720 int providerId) {
6721 Objects.requireNonNull(networkInfo, "networkInfo must not be null");
6722 Objects.requireNonNull(linkProperties, "linkProperties must not be null");
6723 Objects.requireNonNull(networkCapabilities, "networkCapabilities must not be null");
6724 Objects.requireNonNull(initialScore, "initialScore must not be null");
6725 Objects.requireNonNull(networkAgentConfig, "networkAgentConfig must not be null");
6726 if (networkCapabilities.hasTransport(TRANSPORT_TEST)) {
6727 enforceAnyPermissionOf(Manifest.permission.MANAGE_TEST_NETWORKS);
6728 } else {
6729 enforceNetworkFactoryPermission();
6730 }
6731
6732 final int uid = mDeps.getCallingUid();
6733 final long token = Binder.clearCallingIdentity();
6734 try {
6735 return registerNetworkAgentInternal(na, networkInfo, linkProperties,
6736 networkCapabilities, initialScore, networkAgentConfig, providerId, uid);
6737 } finally {
6738 Binder.restoreCallingIdentity(token);
6739 }
6740 }
6741
6742 private Network registerNetworkAgentInternal(INetworkAgent na, NetworkInfo networkInfo,
6743 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
6744 NetworkScore currentScore, NetworkAgentConfig networkAgentConfig, int providerId,
6745 int uid) {
6746 if (networkCapabilities.hasTransport(TRANSPORT_TEST)) {
6747 // Strictly, sanitizing here is unnecessary as the capabilities will be sanitized in
6748 // the call to mixInCapabilities below anyway, but sanitizing here means the NAI never
6749 // sees capabilities that may be malicious, which might prevent mistakes in the future.
6750 networkCapabilities = new NetworkCapabilities(networkCapabilities);
6751 networkCapabilities.restrictCapabilitesForTestNetwork(uid);
6752 }
6753
6754 LinkProperties lp = new LinkProperties(linkProperties);
6755
6756 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
6757 final NetworkAgentInfo nai = new NetworkAgentInfo(na,
6758 new Network(mNetIdManager.reserveNetId()), new NetworkInfo(networkInfo), lp, nc,
6759 currentScore, mContext, mTrackerHandler, new NetworkAgentConfig(networkAgentConfig),
6760 this, mNetd, mDnsResolver, providerId, uid, mLingerDelayMs,
6761 mQosCallbackTracker, mDeps);
6762
6763 // Make sure the LinkProperties and NetworkCapabilities reflect what the agent info says.
6764 processCapabilitiesFromAgent(nai, nc);
6765 nai.getAndSetNetworkCapabilities(mixInCapabilities(nai, nc));
6766 processLinkPropertiesFromAgent(nai, nai.linkProperties);
6767
6768 final String extraInfo = networkInfo.getExtraInfo();
6769 final String name = TextUtils.isEmpty(extraInfo)
6770 ? nai.networkCapabilities.getSsid() : extraInfo;
6771 if (DBG) log("registerNetworkAgent " + nai);
6772 mDeps.getNetworkStack().makeNetworkMonitor(
6773 nai.network, name, new NetworkMonitorCallbacks(nai));
6774 // NetworkAgentInfo registration will finish when the NetworkMonitor is created.
6775 // If the network disconnects or sends any other event before that, messages are deferred by
6776 // NetworkAgent until nai.connect(), which will be called when finalizing the
6777 // registration.
6778 return nai.network;
6779 }
6780
6781 private void handleRegisterNetworkAgent(NetworkAgentInfo nai, INetworkMonitor networkMonitor) {
6782 nai.onNetworkMonitorCreated(networkMonitor);
6783 if (VDBG) log("Got NetworkAgent Messenger");
6784 mNetworkAgentInfos.add(nai);
6785 synchronized (mNetworkForNetId) {
6786 mNetworkForNetId.put(nai.network.getNetId(), nai);
6787 }
6788
6789 try {
6790 networkMonitor.start();
6791 } catch (RemoteException e) {
6792 e.rethrowAsRuntimeException();
6793 }
6794 nai.notifyRegistered();
6795 NetworkInfo networkInfo = nai.networkInfo;
6796 updateNetworkInfo(nai, networkInfo);
6797 updateUids(nai, null, nai.networkCapabilities);
6798 }
6799
6800 private class NetworkOfferInfo implements IBinder.DeathRecipient {
6801 @NonNull public final NetworkOffer offer;
6802
6803 NetworkOfferInfo(@NonNull final NetworkOffer offer) {
6804 this.offer = offer;
6805 }
6806
6807 @Override
6808 public void binderDied() {
6809 mHandler.post(() -> handleUnregisterNetworkOffer(this));
6810 }
6811 }
6812
6813 private boolean isNetworkProviderWithIdRegistered(final int providerId) {
6814 for (final NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
6815 if (npi.providerId == providerId) return true;
6816 }
6817 return false;
6818 }
6819
6820 /**
6821 * Register or update a network offer.
6822 * @param newOffer The new offer. If the callback member is the same as an existing
6823 * offer, it is an update of that offer.
6824 */
6825 private void handleRegisterNetworkOffer(@NonNull final NetworkOffer newOffer) {
6826 ensureRunningOnConnectivityServiceThread();
6827 if (!isNetworkProviderWithIdRegistered(newOffer.providerId)) {
6828 // This may actually happen if a provider updates its score or registers and then
6829 // immediately unregisters. The offer would still be in the handler queue, but the
6830 // provider would have been removed.
6831 if (DBG) log("Received offer from an unregistered provider");
6832 return;
6833 }
6834 final NetworkOfferInfo existingOffer = findNetworkOfferInfoByCallback(newOffer.callback);
6835 if (null != existingOffer) {
6836 handleUnregisterNetworkOffer(existingOffer);
6837 newOffer.migrateFrom(existingOffer.offer);
6838 }
6839 final NetworkOfferInfo noi = new NetworkOfferInfo(newOffer);
6840 try {
6841 noi.offer.callback.asBinder().linkToDeath(noi, 0 /* flags */);
6842 } catch (RemoteException e) {
6843 noi.binderDied();
6844 return;
6845 }
6846 mNetworkOffers.add(noi);
6847 issueNetworkNeeds(noi);
6848 }
6849
6850 private void handleUnregisterNetworkOffer(@NonNull final NetworkOfferInfo noi) {
6851 ensureRunningOnConnectivityServiceThread();
6852 mNetworkOffers.remove(noi);
6853 noi.offer.callback.asBinder().unlinkToDeath(noi, 0 /* flags */);
6854 }
6855
6856 @Nullable private NetworkOfferInfo findNetworkOfferInfoByCallback(
6857 @NonNull final INetworkOfferCallback callback) {
6858 ensureRunningOnConnectivityServiceThread();
6859 for (final NetworkOfferInfo noi : mNetworkOffers) {
6860 if (noi.offer.callback.asBinder().equals(callback.asBinder())) return noi;
6861 }
6862 return null;
6863 }
6864
6865 /**
6866 * Called when receiving LinkProperties directly from a NetworkAgent.
6867 * Stores into |nai| any data coming from the agent that might also be written to the network's
6868 * LinkProperties by ConnectivityService itself. This ensures that the data provided by the
6869 * agent is not lost when updateLinkProperties is called.
6870 * This method should never alter the agent's LinkProperties, only store data in |nai|.
6871 */
6872 private void processLinkPropertiesFromAgent(NetworkAgentInfo nai, LinkProperties lp) {
6873 lp.ensureDirectlyConnectedRoutes();
6874 nai.clatd.setNat64PrefixFromRa(lp.getNat64Prefix());
6875 nai.networkAgentPortalData = lp.getCaptivePortalData();
6876 }
6877
6878 private void updateLinkProperties(NetworkAgentInfo networkAgent, @NonNull LinkProperties newLp,
6879 @NonNull LinkProperties oldLp) {
6880 int netId = networkAgent.network.getNetId();
6881
6882 // The NetworkAgent does not know whether clatd is running on its network or not, or whether
6883 // a NAT64 prefix was discovered by the DNS resolver. Before we do anything else, make sure
6884 // the LinkProperties for the network are accurate.
6885 networkAgent.clatd.fixupLinkProperties(oldLp, newLp);
6886
6887 updateInterfaces(newLp, oldLp, netId, networkAgent.networkCapabilities);
6888
6889 // update filtering rules, need to happen after the interface update so netd knows about the
6890 // new interface (the interface name -> index map becomes initialized)
6891 updateVpnFiltering(newLp, oldLp, networkAgent);
6892
6893 updateMtu(newLp, oldLp);
6894 // TODO - figure out what to do for clat
6895// for (LinkProperties lp : newLp.getStackedLinks()) {
6896// updateMtu(lp, null);
6897// }
6898 if (isDefaultNetwork(networkAgent)) {
6899 updateTcpBufferSizes(newLp.getTcpBufferSizes());
6900 }
6901
6902 updateRoutes(newLp, oldLp, netId);
6903 updateDnses(newLp, oldLp, netId);
6904 // Make sure LinkProperties represents the latest private DNS status.
6905 // This does not need to be done before updateDnses because the
6906 // LinkProperties are not the source of the private DNS configuration.
6907 // updateDnses will fetch the private DNS configuration from DnsManager.
6908 mDnsManager.updatePrivateDnsStatus(netId, newLp);
6909
6910 if (isDefaultNetwork(networkAgent)) {
6911 handleApplyDefaultProxy(newLp.getHttpProxy());
6912 } else {
6913 updateProxy(newLp, oldLp);
6914 }
6915
6916 updateWakeOnLan(newLp);
6917
6918 // Captive portal data is obtained from NetworkMonitor and stored in NetworkAgentInfo.
6919 // It is not always contained in the LinkProperties sent from NetworkAgents, and if it
6920 // does, it needs to be merged here.
6921 newLp.setCaptivePortalData(mergeCaptivePortalData(networkAgent.networkAgentPortalData,
6922 networkAgent.capportApiData));
6923
6924 // TODO - move this check to cover the whole function
6925 if (!Objects.equals(newLp, oldLp)) {
6926 synchronized (networkAgent) {
6927 networkAgent.linkProperties = newLp;
6928 }
6929 // Start or stop DNS64 detection and 464xlat according to network state.
6930 networkAgent.clatd.update();
6931 notifyIfacesChangedForNetworkStats();
6932 networkAgent.networkMonitor().notifyLinkPropertiesChanged(
6933 new LinkProperties(newLp, true /* parcelSensitiveFields */));
6934 if (networkAgent.everConnected) {
6935 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
6936 }
6937 }
6938
6939 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
6940 }
6941
6942 /**
6943 * @param naData captive portal data from NetworkAgent
6944 * @param apiData captive portal data from capport API
6945 */
6946 @Nullable
6947 private CaptivePortalData mergeCaptivePortalData(CaptivePortalData naData,
6948 CaptivePortalData apiData) {
6949 if (naData == null || apiData == null) {
6950 return naData == null ? apiData : naData;
6951 }
6952 final CaptivePortalData.Builder captivePortalBuilder =
6953 new CaptivePortalData.Builder(naData);
6954
6955 if (apiData.isCaptive()) {
6956 captivePortalBuilder.setCaptive(true);
6957 }
6958 if (apiData.isSessionExtendable()) {
6959 captivePortalBuilder.setSessionExtendable(true);
6960 }
6961 if (apiData.getExpiryTimeMillis() >= 0 || apiData.getByteLimit() >= 0) {
6962 // Expiry time, bytes remaining, refresh time all need to come from the same source,
6963 // otherwise data would be inconsistent. Prefer the capport API info if present,
6964 // as it can generally be refreshed more often.
6965 captivePortalBuilder.setExpiryTime(apiData.getExpiryTimeMillis());
6966 captivePortalBuilder.setBytesRemaining(apiData.getByteLimit());
6967 captivePortalBuilder.setRefreshTime(apiData.getRefreshTimeMillis());
6968 } else if (naData.getExpiryTimeMillis() < 0 && naData.getByteLimit() < 0) {
6969 // No source has time / bytes remaining information: surface the newest refresh time
6970 // for other fields
6971 captivePortalBuilder.setRefreshTime(
6972 Math.max(naData.getRefreshTimeMillis(), apiData.getRefreshTimeMillis()));
6973 }
6974
6975 // Prioritize the user portal URL from the network agent if the source is authenticated.
6976 if (apiData.getUserPortalUrl() != null && naData.getUserPortalUrlSource()
6977 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
6978 captivePortalBuilder.setUserPortalUrl(apiData.getUserPortalUrl(),
6979 apiData.getUserPortalUrlSource());
6980 }
6981 // Prioritize the venue information URL from the network agent if the source is
6982 // authenticated.
6983 if (apiData.getVenueInfoUrl() != null && naData.getVenueInfoUrlSource()
6984 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
6985 captivePortalBuilder.setVenueInfoUrl(apiData.getVenueInfoUrl(),
6986 apiData.getVenueInfoUrlSource());
6987 }
6988 return captivePortalBuilder.build();
6989 }
6990
6991 private void wakeupModifyInterface(String iface, NetworkCapabilities caps, boolean add) {
6992 // Marks are only available on WiFi interfaces. Checking for
6993 // marks on unsupported interfaces is harmless.
6994 if (!caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
6995 return;
6996 }
6997
6998 int mark = mResources.get().getInteger(R.integer.config_networkWakeupPacketMark);
6999 int mask = mResources.get().getInteger(R.integer.config_networkWakeupPacketMask);
7000
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00007001 // Mask/mark of zero will not detect anything interesting.
7002 // Don't install rules unless both values are nonzero.
7003 if (mark == 0 || mask == 0) {
7004 return;
7005 }
7006
7007 final String prefix = "iface:" + iface;
7008 try {
7009 if (add) {
7010 mNetd.wakeupAddInterface(iface, prefix, mark, mask);
7011 } else {
7012 mNetd.wakeupDelInterface(iface, prefix, mark, mask);
7013 }
7014 } catch (Exception e) {
7015 loge("Exception modifying wakeup packet monitoring: " + e);
7016 }
7017
7018 }
7019
7020 private void updateInterfaces(final @Nullable LinkProperties newLp,
7021 final @Nullable LinkProperties oldLp, final int netId,
7022 final @NonNull NetworkCapabilities caps) {
7023 final CompareResult<String> interfaceDiff = new CompareResult<>(
7024 oldLp != null ? oldLp.getAllInterfaceNames() : null,
7025 newLp != null ? newLp.getAllInterfaceNames() : null);
7026 if (!interfaceDiff.added.isEmpty()) {
7027 for (final String iface : interfaceDiff.added) {
7028 try {
7029 if (DBG) log("Adding iface " + iface + " to network " + netId);
7030 mNetd.networkAddInterface(netId, iface);
7031 wakeupModifyInterface(iface, caps, true);
7032 mDeps.reportNetworkInterfaceForTransports(mContext, iface,
7033 caps.getTransportTypes());
7034 } catch (Exception e) {
7035 logw("Exception adding interface: " + e);
7036 }
7037 }
7038 }
7039 for (final String iface : interfaceDiff.removed) {
7040 try {
7041 if (DBG) log("Removing iface " + iface + " from network " + netId);
7042 wakeupModifyInterface(iface, caps, false);
7043 mNetd.networkRemoveInterface(netId, iface);
7044 } catch (Exception e) {
7045 loge("Exception removing interface: " + e);
7046 }
7047 }
7048 }
7049
7050 // TODO: move to frameworks/libs/net.
7051 private RouteInfoParcel convertRouteInfo(RouteInfo route) {
7052 final String nextHop;
7053
7054 switch (route.getType()) {
7055 case RouteInfo.RTN_UNICAST:
7056 if (route.hasGateway()) {
7057 nextHop = route.getGateway().getHostAddress();
7058 } else {
7059 nextHop = INetd.NEXTHOP_NONE;
7060 }
7061 break;
7062 case RouteInfo.RTN_UNREACHABLE:
7063 nextHop = INetd.NEXTHOP_UNREACHABLE;
7064 break;
7065 case RouteInfo.RTN_THROW:
7066 nextHop = INetd.NEXTHOP_THROW;
7067 break;
7068 default:
7069 nextHop = INetd.NEXTHOP_NONE;
7070 break;
7071 }
7072
7073 final RouteInfoParcel rip = new RouteInfoParcel();
7074 rip.ifName = route.getInterface();
7075 rip.destination = route.getDestination().toString();
7076 rip.nextHop = nextHop;
7077 rip.mtu = route.getMtu();
7078
7079 return rip;
7080 }
7081
7082 /**
7083 * Have netd update routes from oldLp to newLp.
7084 * @return true if routes changed between oldLp and newLp
7085 */
7086 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
7087 // compare the route diff to determine which routes have been updated
7088 final CompareOrUpdateResult<RouteInfo.RouteKey, RouteInfo> routeDiff =
7089 new CompareOrUpdateResult<>(
7090 oldLp != null ? oldLp.getAllRoutes() : null,
7091 newLp != null ? newLp.getAllRoutes() : null,
7092 (r) -> r.getRouteKey());
7093
7094 // add routes before removing old in case it helps with continuous connectivity
7095
7096 // do this twice, adding non-next-hop routes first, then routes they are dependent on
7097 for (RouteInfo route : routeDiff.added) {
7098 if (route.hasGateway()) continue;
7099 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
7100 try {
7101 mNetd.networkAddRouteParcel(netId, convertRouteInfo(route));
7102 } catch (Exception e) {
7103 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
7104 loge("Exception in networkAddRouteParcel for non-gateway: " + e);
7105 }
7106 }
7107 }
7108 for (RouteInfo route : routeDiff.added) {
7109 if (!route.hasGateway()) continue;
7110 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
7111 try {
7112 mNetd.networkAddRouteParcel(netId, convertRouteInfo(route));
7113 } catch (Exception e) {
7114 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
7115 loge("Exception in networkAddRouteParcel for gateway: " + e);
7116 }
7117 }
7118 }
7119
7120 for (RouteInfo route : routeDiff.removed) {
7121 if (VDBG || DDBG) log("Removing Route [" + route + "] from network " + netId);
7122 try {
7123 mNetd.networkRemoveRouteParcel(netId, convertRouteInfo(route));
7124 } catch (Exception e) {
7125 loge("Exception in networkRemoveRouteParcel: " + e);
7126 }
7127 }
7128
7129 for (RouteInfo route : routeDiff.updated) {
7130 if (VDBG || DDBG) log("Updating Route [" + route + "] from network " + netId);
7131 try {
7132 mNetd.networkUpdateRouteParcel(netId, convertRouteInfo(route));
7133 } catch (Exception e) {
7134 loge("Exception in networkUpdateRouteParcel: " + e);
7135 }
7136 }
7137 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty()
7138 || !routeDiff.updated.isEmpty();
7139 }
7140
7141 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
7142 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
7143 return; // no updating necessary
7144 }
7145
7146 if (DBG) {
7147 final Collection<InetAddress> dnses = newLp.getDnsServers();
7148 log("Setting DNS servers for network " + netId + " to " + dnses);
7149 }
7150 try {
7151 mDnsManager.noteDnsServersForNetwork(netId, newLp);
7152 mDnsManager.flushVmDnsCache();
7153 } catch (Exception e) {
7154 loge("Exception in setDnsConfigurationForNetwork: " + e);
7155 }
7156 }
7157
7158 private void updateVpnFiltering(LinkProperties newLp, LinkProperties oldLp,
7159 NetworkAgentInfo nai) {
7160 final String oldIface = oldLp != null ? oldLp.getInterfaceName() : null;
7161 final String newIface = newLp != null ? newLp.getInterfaceName() : null;
7162 final boolean wasFiltering = requiresVpnIsolation(nai, nai.networkCapabilities, oldLp);
7163 final boolean needsFiltering = requiresVpnIsolation(nai, nai.networkCapabilities, newLp);
7164
7165 if (!wasFiltering && !needsFiltering) {
7166 // Nothing to do.
7167 return;
7168 }
7169
7170 if (Objects.equals(oldIface, newIface) && (wasFiltering == needsFiltering)) {
7171 // Nothing changed.
7172 return;
7173 }
7174
7175 final Set<UidRange> ranges = nai.networkCapabilities.getUidRanges();
7176 final int vpnAppUid = nai.networkCapabilities.getOwnerUid();
7177 // TODO: this create a window of opportunity for apps to receive traffic between the time
7178 // when the old rules are removed and the time when new rules are added. To fix this,
7179 // make eBPF support two allowlisted interfaces so here new rules can be added before the
7180 // old rules are being removed.
7181 if (wasFiltering) {
7182 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, ranges, vpnAppUid);
7183 }
7184 if (needsFiltering) {
7185 mPermissionMonitor.onVpnUidRangesAdded(newIface, ranges, vpnAppUid);
7186 }
7187 }
7188
7189 private void updateWakeOnLan(@NonNull LinkProperties lp) {
7190 if (mWolSupportedInterfaces == null) {
7191 mWolSupportedInterfaces = new ArraySet<>(mResources.get().getStringArray(
7192 R.array.config_wakeonlan_supported_interfaces));
7193 }
7194 lp.setWakeOnLanSupported(mWolSupportedInterfaces.contains(lp.getInterfaceName()));
7195 }
7196
7197 private int getNetworkPermission(NetworkCapabilities nc) {
7198 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
7199 return INetd.PERMISSION_SYSTEM;
7200 }
7201 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
7202 return INetd.PERMISSION_NETWORK;
7203 }
7204 return INetd.PERMISSION_NONE;
7205 }
7206
7207 private void updateNetworkPermissions(@NonNull final NetworkAgentInfo nai,
7208 @NonNull final NetworkCapabilities newNc) {
7209 final int oldPermission = getNetworkPermission(nai.networkCapabilities);
7210 final int newPermission = getNetworkPermission(newNc);
7211 if (oldPermission != newPermission && nai.created && !nai.isVPN()) {
7212 try {
7213 mNetd.networkSetPermissionForNetwork(nai.network.getNetId(), newPermission);
7214 } catch (RemoteException | ServiceSpecificException e) {
7215 loge("Exception in networkSetPermissionForNetwork: " + e);
7216 }
7217 }
7218 }
7219
7220 /**
7221 * Called when receiving NetworkCapabilities directly from a NetworkAgent.
7222 * Stores into |nai| any data coming from the agent that might also be written to the network's
7223 * NetworkCapabilities by ConnectivityService itself. This ensures that the data provided by the
7224 * agent is not lost when updateCapabilities is called.
7225 * This method should never alter the agent's NetworkCapabilities, only store data in |nai|.
7226 */
7227 private void processCapabilitiesFromAgent(NetworkAgentInfo nai, NetworkCapabilities nc) {
7228 // Note: resetting the owner UID before storing the agent capabilities in NAI means that if
7229 // the agent attempts to change the owner UID, then nai.declaredCapabilities will not
7230 // actually be the same as the capabilities sent by the agent. Still, it is safer to reset
7231 // the owner UID here and behave as if the agent had never tried to change it.
7232 if (nai.networkCapabilities.getOwnerUid() != nc.getOwnerUid()) {
7233 Log.e(TAG, nai.toShortString() + ": ignoring attempt to change owner from "
7234 + nai.networkCapabilities.getOwnerUid() + " to " + nc.getOwnerUid());
7235 nc.setOwnerUid(nai.networkCapabilities.getOwnerUid());
7236 }
7237 nai.declaredCapabilities = new NetworkCapabilities(nc);
7238 }
7239
7240 /** Modifies |newNc| based on the capabilities of |underlyingNetworks| and |agentCaps|. */
7241 @VisibleForTesting
7242 void applyUnderlyingCapabilities(@Nullable Network[] underlyingNetworks,
7243 @NonNull NetworkCapabilities agentCaps, @NonNull NetworkCapabilities newNc) {
7244 underlyingNetworks = underlyingNetworksOrDefault(
7245 agentCaps.getOwnerUid(), underlyingNetworks);
7246 long transportTypes = NetworkCapabilitiesUtils.packBits(agentCaps.getTransportTypes());
7247 int downKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
7248 int upKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
7249 // metered if any underlying is metered, or originally declared metered by the agent.
7250 boolean metered = !agentCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
7251 boolean roaming = false; // roaming if any underlying is roaming
7252 boolean congested = false; // congested if any underlying is congested
7253 boolean suspended = true; // suspended if all underlying are suspended
7254
7255 boolean hadUnderlyingNetworks = false;
7256 if (null != underlyingNetworks) {
7257 for (Network underlyingNetwork : underlyingNetworks) {
7258 final NetworkAgentInfo underlying =
7259 getNetworkAgentInfoForNetwork(underlyingNetwork);
7260 if (underlying == null) continue;
7261
7262 final NetworkCapabilities underlyingCaps = underlying.networkCapabilities;
7263 hadUnderlyingNetworks = true;
7264 for (int underlyingType : underlyingCaps.getTransportTypes()) {
7265 transportTypes |= 1L << underlyingType;
7266 }
7267
7268 // Merge capabilities of this underlying network. For bandwidth, assume the
7269 // worst case.
7270 downKbps = NetworkCapabilities.minBandwidth(downKbps,
7271 underlyingCaps.getLinkDownstreamBandwidthKbps());
7272 upKbps = NetworkCapabilities.minBandwidth(upKbps,
7273 underlyingCaps.getLinkUpstreamBandwidthKbps());
7274 // If this underlying network is metered, the VPN is metered (it may cost money
7275 // to send packets on this network).
7276 metered |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
7277 // If this underlying network is roaming, the VPN is roaming (the billing structure
7278 // is different than the usual, local one).
7279 roaming |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_ROAMING);
7280 // If this underlying network is congested, the VPN is congested (the current
7281 // condition of the network affects the performance of this network).
7282 congested |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_CONGESTED);
7283 // If this network is not suspended, the VPN is not suspended (the VPN
7284 // is able to transfer some data).
7285 suspended &= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
7286 }
7287 }
7288 if (!hadUnderlyingNetworks) {
7289 // No idea what the underlying networks are; assume reasonable defaults
7290 metered = true;
7291 roaming = false;
7292 congested = false;
7293 suspended = false;
7294 }
7295
7296 newNc.setTransportTypes(NetworkCapabilitiesUtils.unpackBits(transportTypes));
7297 newNc.setLinkDownstreamBandwidthKbps(downKbps);
7298 newNc.setLinkUpstreamBandwidthKbps(upKbps);
7299 newNc.setCapability(NET_CAPABILITY_NOT_METERED, !metered);
7300 newNc.setCapability(NET_CAPABILITY_NOT_ROAMING, !roaming);
7301 newNc.setCapability(NET_CAPABILITY_NOT_CONGESTED, !congested);
7302 newNc.setCapability(NET_CAPABILITY_NOT_SUSPENDED, !suspended);
7303 }
7304
7305 /**
7306 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
7307 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
7308 * and foreground status).
7309 */
7310 @NonNull
7311 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
7312 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
7313 // Don't complain for VPNs since they're not driven by requests and there is no risk of
7314 // causing a connect/teardown loop.
7315 // TODO: remove this altogether and make it the responsibility of the NetworkProviders to
7316 // avoid connect/teardown loops.
7317 if (nai.everConnected &&
7318 !nai.isVPN() &&
7319 !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
7320 // TODO: consider not complaining when a network agent degrades its capabilities if this
7321 // does not cause any request (that is not a listen) currently matching that agent to
7322 // stop being matched by the updated agent.
7323 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
7324 if (!TextUtils.isEmpty(diff)) {
7325 Log.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
7326 }
7327 }
7328
7329 // Don't modify caller's NetworkCapabilities.
7330 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
7331 if (nai.lastValidated) {
7332 newNc.addCapability(NET_CAPABILITY_VALIDATED);
7333 } else {
7334 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
7335 }
7336 if (nai.lastCaptivePortalDetected) {
7337 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
7338 } else {
7339 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
7340 }
7341 if (nai.isBackgroundNetwork()) {
7342 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
7343 } else {
7344 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
7345 }
7346 if (nai.partialConnectivity) {
7347 newNc.addCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
7348 } else {
7349 newNc.removeCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
7350 }
7351 newNc.setPrivateDnsBroken(nai.networkCapabilities.isPrivateDnsBroken());
7352
7353 // TODO : remove this once all factories are updated to send NOT_SUSPENDED and NOT_ROAMING
7354 if (!newNc.hasTransport(TRANSPORT_CELLULAR)) {
7355 newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
7356 newNc.addCapability(NET_CAPABILITY_NOT_ROAMING);
7357 }
7358
Lorenzo Colittibd079452021-07-02 11:47:57 +09007359 if (nai.propagateUnderlyingCapabilities()) {
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00007360 applyUnderlyingCapabilities(nai.declaredUnderlyingNetworks, nai.declaredCapabilities,
7361 newNc);
7362 }
7363
7364 return newNc;
7365 }
7366
7367 private void updateNetworkInfoForRoamingAndSuspended(NetworkAgentInfo nai,
7368 NetworkCapabilities prevNc, NetworkCapabilities newNc) {
7369 final boolean prevSuspended = !prevNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
7370 final boolean suspended = !newNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
7371 final boolean prevRoaming = !prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
7372 final boolean roaming = !newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
7373 if (prevSuspended != suspended) {
7374 // TODO (b/73132094) : remove this call once the few users of onSuspended and
7375 // onResumed have been removed.
7376 notifyNetworkCallbacks(nai, suspended ? ConnectivityManager.CALLBACK_SUSPENDED
7377 : ConnectivityManager.CALLBACK_RESUMED);
7378 }
7379 if (prevSuspended != suspended || prevRoaming != roaming) {
7380 // updateNetworkInfo will mix in the suspended info from the capabilities and
7381 // take appropriate action for the network having possibly changed state.
7382 updateNetworkInfo(nai, nai.networkInfo);
7383 }
7384 }
7385
7386 /**
7387 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
7388 *
7389 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
7390 * capabilities we manage and store in {@code nai}, such as validated status and captive
7391 * portal status)
7392 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
7393 * potentially triggers rematches.
7394 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
7395 * change.)
7396 *
7397 * @param oldScore score of the network before any of the changes that prompted us
7398 * to call this function.
7399 * @param nai the network having its capabilities updated.
7400 * @param nc the new network capabilities.
7401 */
7402 private void updateCapabilities(final int oldScore, @NonNull final NetworkAgentInfo nai,
7403 @NonNull final NetworkCapabilities nc) {
7404 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
7405 if (Objects.equals(nai.networkCapabilities, newNc)) return;
7406 updateNetworkPermissions(nai, newNc);
7407 final NetworkCapabilities prevNc = nai.getAndSetNetworkCapabilities(newNc);
7408
7409 updateUids(nai, prevNc, newNc);
7410 nai.updateScoreForNetworkAgentUpdate();
7411
7412 if (nai.getCurrentScore() == oldScore && newNc.equalRequestableCapabilities(prevNc)) {
7413 // If the requestable capabilities haven't changed, and the score hasn't changed, then
7414 // the change we're processing can't affect any requests, it can only affect the listens
7415 // on this network. We might have been called by rematchNetworkAndRequests when a
7416 // network changed foreground state.
7417 processListenRequests(nai);
7418 } else {
7419 // If the requestable capabilities have changed or the score changed, we can't have been
7420 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
7421 rematchAllNetworksAndRequests();
7422 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
7423 }
7424 updateNetworkInfoForRoamingAndSuspended(nai, prevNc, newNc);
7425
7426 final boolean oldMetered = prevNc.isMetered();
7427 final boolean newMetered = newNc.isMetered();
7428 final boolean meteredChanged = oldMetered != newMetered;
7429
7430 if (meteredChanged) {
7431 maybeNotifyNetworkBlocked(nai, oldMetered, newMetered,
7432 mVpnBlockedUidRanges, mVpnBlockedUidRanges);
7433 }
7434
7435 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING)
7436 != newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
7437
7438 // Report changes that are interesting for network statistics tracking.
7439 if (meteredChanged || roamingChanged) {
7440 notifyIfacesChangedForNetworkStats();
7441 }
7442
7443 // This network might have been underlying another network. Propagate its capabilities.
7444 propagateUnderlyingNetworkCapabilities(nai.network);
7445
7446 if (!newNc.equalsTransportTypes(prevNc)) {
7447 mDnsManager.updateTransportsForNetwork(
7448 nai.network.getNetId(), newNc.getTransportTypes());
7449 }
lucaslin53e8a262021-06-08 01:43:59 +08007450
7451 maybeSendProxyBroadcast(nai, prevNc, newNc);
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00007452 }
7453
7454 /** Convenience method to update the capabilities for a given network. */
7455 private void updateCapabilitiesForNetwork(NetworkAgentInfo nai) {
7456 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
7457 }
7458
7459 /**
7460 * Returns whether VPN isolation (ingress interface filtering) should be applied on the given
7461 * network.
7462 *
7463 * Ingress interface filtering enforces that all apps under the given network can only receive
7464 * packets from the network's interface (and loopback). This is important for VPNs because
7465 * apps that cannot bypass a fully-routed VPN shouldn't be able to receive packets from any
7466 * non-VPN interfaces.
7467 *
7468 * As a result, this method should return true iff
7469 * 1. the network is an app VPN (not legacy VPN)
7470 * 2. the VPN does not allow bypass
7471 * 3. the VPN is fully-routed
7472 * 4. the VPN interface is non-null
7473 *
7474 * @see INetd#firewallAddUidInterfaceRules
7475 * @see INetd#firewallRemoveUidInterfaceRules
7476 */
7477 private boolean requiresVpnIsolation(@NonNull NetworkAgentInfo nai, NetworkCapabilities nc,
7478 LinkProperties lp) {
7479 if (nc == null || lp == null) return false;
7480 return nai.isVPN()
7481 && !nai.networkAgentConfig.allowBypass
7482 && nc.getOwnerUid() != Process.SYSTEM_UID
7483 && lp.getInterfaceName() != null
7484 && (lp.hasIpv4DefaultRoute() || lp.hasIpv4UnreachableDefaultRoute())
7485 && (lp.hasIpv6DefaultRoute() || lp.hasIpv6UnreachableDefaultRoute());
7486 }
7487
7488 private static UidRangeParcel[] toUidRangeStableParcels(final @NonNull Set<UidRange> ranges) {
7489 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.size()];
7490 int index = 0;
7491 for (UidRange range : ranges) {
7492 stableRanges[index] = new UidRangeParcel(range.start, range.stop);
7493 index++;
7494 }
7495 return stableRanges;
7496 }
7497
7498 private static UidRangeParcel[] toUidRangeStableParcels(UidRange[] ranges) {
7499 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.length];
7500 for (int i = 0; i < ranges.length; i++) {
7501 stableRanges[i] = new UidRangeParcel(ranges[i].start, ranges[i].stop);
7502 }
7503 return stableRanges;
7504 }
7505
7506 private void maybeCloseSockets(NetworkAgentInfo nai, UidRangeParcel[] ranges,
7507 int[] exemptUids) {
7508 if (nai.isVPN() && !nai.networkAgentConfig.allowBypass) {
7509 try {
7510 mNetd.socketDestroy(ranges, exemptUids);
7511 } catch (Exception e) {
7512 loge("Exception in socket destroy: ", e);
7513 }
7514 }
7515 }
7516
paulhude5efb92021-05-26 21:56:03 +08007517 private void updateVpnUidRanges(boolean add, NetworkAgentInfo nai, Set<UidRange> uidRanges) {
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00007518 int[] exemptUids = new int[2];
7519 // TODO: Excluding VPN_UID is necessary in order to not to kill the TCP connection used
7520 // by PPTP. Fix this by making Vpn set the owner UID to VPN_UID instead of system when
7521 // starting a legacy VPN, and remove VPN_UID here. (b/176542831)
7522 exemptUids[0] = VPN_UID;
7523 exemptUids[1] = nai.networkCapabilities.getOwnerUid();
7524 UidRangeParcel[] ranges = toUidRangeStableParcels(uidRanges);
7525
7526 maybeCloseSockets(nai, ranges, exemptUids);
7527 try {
7528 if (add) {
paulhude2a2392021-06-09 16:11:35 +08007529 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08007530 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00007531 } else {
paulhude2a2392021-06-09 16:11:35 +08007532 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08007533 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00007534 }
7535 } catch (Exception e) {
7536 loge("Exception while " + (add ? "adding" : "removing") + " uid ranges " + uidRanges +
7537 " on netId " + nai.network.netId + ". " + e);
7538 }
7539 maybeCloseSockets(nai, ranges, exemptUids);
7540 }
7541
lucaslin53e8a262021-06-08 01:43:59 +08007542 private boolean isProxySetOnAnyDefaultNetwork() {
7543 ensureRunningOnConnectivityServiceThread();
7544 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
7545 final NetworkAgentInfo nai = nri.getSatisfier();
7546 if (nai != null && nai.linkProperties.getHttpProxy() != null) {
7547 return true;
7548 }
7549 }
7550 return false;
7551 }
7552
7553 private void maybeSendProxyBroadcast(NetworkAgentInfo nai, NetworkCapabilities prevNc,
7554 NetworkCapabilities newNc) {
7555 // When the apps moved from/to a VPN, a proxy broadcast is needed to inform the apps that
7556 // the proxy might be changed since the default network satisfied by the apps might also
7557 // changed.
7558 // TODO: Try to track the default network that apps use and only send a proxy broadcast when
7559 // that happens to prevent false alarms.
7560 if (nai.isVPN() && nai.everConnected && !NetworkCapabilities.hasSameUids(prevNc, newNc)
7561 && (nai.linkProperties.getHttpProxy() != null || isProxySetOnAnyDefaultNetwork())) {
7562 mProxyTracker.sendProxyBroadcast();
7563 }
7564 }
7565
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00007566 private void updateUids(NetworkAgentInfo nai, NetworkCapabilities prevNc,
7567 NetworkCapabilities newNc) {
7568 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUidRanges();
7569 Set<UidRange> newRanges = null == newNc ? null : newNc.getUidRanges();
7570 if (null == prevRanges) prevRanges = new ArraySet<>();
7571 if (null == newRanges) newRanges = new ArraySet<>();
7572 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
7573
7574 prevRanges.removeAll(newRanges);
7575 newRanges.removeAll(prevRangesCopy);
7576
7577 try {
7578 // When updating the VPN uid routing rules, add the new range first then remove the old
7579 // range. If old range were removed first, there would be a window between the old
7580 // range being removed and the new range being added, during which UIDs contained
7581 // in both ranges are not subject to any VPN routing rules. Adding new range before
7582 // removing old range works because, unlike the filtering rules below, it's possible to
7583 // add duplicate UID routing rules.
7584 // TODO: calculate the intersection of add & remove. Imagining that we are trying to
7585 // remove uid 3 from a set containing 1-5. Intersection of the prev and new sets is:
7586 // [1-5] & [1-2],[4-5] == [3]
7587 // Then we can do:
7588 // maybeCloseSockets([3])
7589 // mNetd.networkAddUidRanges([1-2],[4-5])
7590 // mNetd.networkRemoveUidRanges([1-5])
7591 // maybeCloseSockets([3])
7592 // This can prevent the sockets of uid 1-2, 4-5 from being closed. It also reduce the
7593 // number of binder calls from 6 to 4.
7594 if (!newRanges.isEmpty()) {
paulhude5efb92021-05-26 21:56:03 +08007595 updateVpnUidRanges(true, nai, newRanges);
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00007596 }
7597 if (!prevRanges.isEmpty()) {
paulhude5efb92021-05-26 21:56:03 +08007598 updateVpnUidRanges(false, nai, prevRanges);
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00007599 }
7600 final boolean wasFiltering = requiresVpnIsolation(nai, prevNc, nai.linkProperties);
7601 final boolean shouldFilter = requiresVpnIsolation(nai, newNc, nai.linkProperties);
7602 final String iface = nai.linkProperties.getInterfaceName();
7603 // For VPN uid interface filtering, old ranges need to be removed before new ranges can
7604 // be added, due to the range being expanded and stored as individual UIDs. For example
7605 // the UIDs might be updated from [0, 99999] to ([0, 10012], [10014, 99999]) which means
7606 // prevRanges = [0, 99999] while newRanges = [0, 10012], [10014, 99999]. If prevRanges
7607 // were added first and then newRanges got removed later, there would be only one uid
7608 // 10013 left. A consequence of removing old ranges before adding new ranges is that
7609 // there is now a window of opportunity when the UIDs are not subject to any filtering.
7610 // Note that this is in contrast with the (more robust) update of VPN routing rules
7611 // above, where the addition of new ranges happens before the removal of old ranges.
7612 // TODO Fix this window by computing an accurate diff on Set<UidRange>, so the old range
7613 // to be removed will never overlap with the new range to be added.
7614 if (wasFiltering && !prevRanges.isEmpty()) {
7615 mPermissionMonitor.onVpnUidRangesRemoved(iface, prevRanges, prevNc.getOwnerUid());
7616 }
7617 if (shouldFilter && !newRanges.isEmpty()) {
7618 mPermissionMonitor.onVpnUidRangesAdded(iface, newRanges, newNc.getOwnerUid());
7619 }
7620 } catch (Exception e) {
7621 // Never crash!
7622 loge("Exception in updateUids: ", e);
7623 }
7624 }
7625
7626 public void handleUpdateLinkProperties(NetworkAgentInfo nai, LinkProperties newLp) {
7627 ensureRunningOnConnectivityServiceThread();
7628
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09007629 if (!mNetworkAgentInfos.contains(nai)) {
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00007630 // Ignore updates for disconnected networks
7631 return;
7632 }
7633 if (VDBG || DDBG) {
7634 log("Update of LinkProperties for " + nai.toShortString()
7635 + "; created=" + nai.created
7636 + "; everConnected=" + nai.everConnected);
7637 }
7638 // TODO: eliminate this defensive copy after confirming that updateLinkProperties does not
7639 // modify its oldLp parameter.
7640 updateLinkProperties(nai, newLp, new LinkProperties(nai.linkProperties));
7641 }
7642
7643 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
7644 int notificationType) {
7645 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
7646 Intent intent = new Intent();
7647 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
7648 // If apps could file multi-layer requests with PendingIntents, they'd need to know
7649 // which of the layer is satisfied alongside with some ID for the request. Hence, if
7650 // such an API is ever implemented, there is no doubt the right request to send in
Remi NGUYEN VAN1e238a82021-06-25 16:38:05 +09007651 // EXTRA_NETWORK_REQUEST is the active request, and whatever ID would be added would
7652 // need to be sent as a separate extra.
7653 final NetworkRequest req = nri.isMultilayerRequest()
7654 ? nri.getActiveRequest()
7655 // Non-multilayer listen requests do not have an active request
7656 : nri.mRequests.get(0);
7657 if (req == null) {
7658 Log.wtf(TAG, "No request in NRI " + nri);
7659 }
7660 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, req);
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00007661 nri.mPendingIntentSent = true;
7662 sendIntent(nri.mPendingIntent, intent);
7663 }
7664 // else not handled
7665 }
7666
7667 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
7668 mPendingIntentWakeLock.acquire();
7669 try {
7670 if (DBG) log("Sending " + pendingIntent);
7671 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
7672 } catch (PendingIntent.CanceledException e) {
7673 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
7674 mPendingIntentWakeLock.release();
7675 releasePendingNetworkRequest(pendingIntent);
7676 }
7677 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
7678 }
7679
7680 @Override
7681 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
7682 String resultData, Bundle resultExtras) {
7683 if (DBG) log("Finished sending " + pendingIntent);
7684 mPendingIntentWakeLock.release();
7685 // Release with a delay so the receiving client has an opportunity to put in its
7686 // own request.
7687 releasePendingNetworkRequestWithDelay(pendingIntent);
7688 }
7689
7690 private void callCallbackForRequest(@NonNull final NetworkRequestInfo nri,
7691 @NonNull final NetworkAgentInfo networkAgent, final int notificationType,
7692 final int arg1) {
7693 if (nri.mMessenger == null) {
7694 // Default request has no msgr. Also prevents callbacks from being invoked for
7695 // NetworkRequestInfos registered with ConnectivityDiagnostics requests. Those callbacks
7696 // are Type.LISTEN, but should not have NetworkCallbacks invoked.
7697 return;
7698 }
7699 Bundle bundle = new Bundle();
7700 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
7701 // TODO: check if defensive copies of data is needed.
7702 final NetworkRequest nrForCallback = nri.getNetworkRequestForCallback();
7703 putParcelable(bundle, nrForCallback);
7704 Message msg = Message.obtain();
7705 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
7706 putParcelable(bundle, networkAgent.network);
7707 }
7708 final boolean includeLocationSensitiveInfo =
7709 (nri.mCallbackFlags & NetworkCallback.FLAG_INCLUDE_LOCATION_INFO) != 0;
7710 switch (notificationType) {
7711 case ConnectivityManager.CALLBACK_AVAILABLE: {
7712 final NetworkCapabilities nc =
7713 networkCapabilitiesRestrictedForCallerPermissions(
7714 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
7715 putParcelable(
7716 bundle,
7717 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
7718 nc, includeLocationSensitiveInfo, nri.mPid, nri.mUid,
7719 nrForCallback.getRequestorPackageName(),
7720 nri.mCallingAttributionTag));
7721 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
7722 networkAgent.linkProperties, nri.mPid, nri.mUid));
7723 // For this notification, arg1 contains the blocked status.
7724 msg.arg1 = arg1;
7725 break;
7726 }
7727 case ConnectivityManager.CALLBACK_LOSING: {
7728 msg.arg1 = arg1;
7729 break;
7730 }
7731 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
7732 // networkAgent can't be null as it has been accessed a few lines above.
7733 final NetworkCapabilities netCap =
7734 networkCapabilitiesRestrictedForCallerPermissions(
7735 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
7736 putParcelable(
7737 bundle,
7738 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
7739 netCap, includeLocationSensitiveInfo, nri.mPid, nri.mUid,
7740 nrForCallback.getRequestorPackageName(),
7741 nri.mCallingAttributionTag));
7742 break;
7743 }
7744 case ConnectivityManager.CALLBACK_IP_CHANGED: {
7745 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
7746 networkAgent.linkProperties, nri.mPid, nri.mUid));
7747 break;
7748 }
7749 case ConnectivityManager.CALLBACK_BLK_CHANGED: {
7750 maybeLogBlockedStatusChanged(nri, networkAgent.network, arg1);
7751 msg.arg1 = arg1;
7752 break;
7753 }
7754 }
7755 msg.what = notificationType;
7756 msg.setData(bundle);
7757 try {
7758 if (VDBG) {
7759 String notification = ConnectivityManager.getCallbackName(notificationType);
7760 log("sending notification " + notification + " for " + nrForCallback);
7761 }
7762 nri.mMessenger.send(msg);
7763 } catch (RemoteException e) {
7764 // may occur naturally in the race of binder death.
7765 loge("RemoteException caught trying to send a callback msg for " + nrForCallback);
7766 }
7767 }
7768
7769 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
7770 bundle.putParcelable(t.getClass().getSimpleName(), t);
7771 }
7772
7773 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
7774 if (nai.numRequestNetworkRequests() != 0) {
7775 for (int i = 0; i < nai.numNetworkRequests(); i++) {
7776 NetworkRequest nr = nai.requestAt(i);
7777 // Ignore listening and track default requests.
7778 if (!nr.isRequest()) continue;
7779 loge("Dead network still had at least " + nr);
7780 break;
7781 }
7782 }
7783 nai.disconnect();
7784 }
7785
7786 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
7787 if (oldNetwork == null) {
7788 loge("Unknown NetworkAgentInfo in handleLingerComplete");
7789 return;
7790 }
7791 if (DBG) log("handleLingerComplete for " + oldNetwork.toShortString());
7792
7793 // If we get here it means that the last linger timeout for this network expired. So there
7794 // must be no other active linger timers, and we must stop lingering.
7795 oldNetwork.clearInactivityState();
7796
7797 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
7798 // Tear the network down.
7799 teardownUnneededNetwork(oldNetwork);
7800 } else {
7801 // Put the network in the background if it doesn't satisfy any foreground request.
7802 updateCapabilitiesForNetwork(oldNetwork);
7803 }
7804 }
7805
7806 private void processDefaultNetworkChanges(@NonNull final NetworkReassignment changes) {
7807 boolean isDefaultChanged = false;
7808 for (final NetworkRequestInfo defaultRequestInfo : mDefaultNetworkRequests) {
7809 final NetworkReassignment.RequestReassignment reassignment =
7810 changes.getReassignment(defaultRequestInfo);
7811 if (null == reassignment) {
7812 continue;
7813 }
7814 // reassignment only contains those instances where the satisfying network changed.
7815 isDefaultChanged = true;
7816 // Notify system services of the new default.
7817 makeDefault(defaultRequestInfo, reassignment.mOldNetwork, reassignment.mNewNetwork);
7818 }
7819
7820 if (isDefaultChanged) {
7821 // Hold a wakelock for a short time to help apps in migrating to a new default.
7822 scheduleReleaseNetworkTransitionWakelock();
7823 }
7824 }
7825
7826 private void makeDefault(@NonNull final NetworkRequestInfo nri,
7827 @Nullable final NetworkAgentInfo oldDefaultNetwork,
7828 @Nullable final NetworkAgentInfo newDefaultNetwork) {
7829 if (DBG) {
7830 log("Switching to new default network for: " + nri + " using " + newDefaultNetwork);
7831 }
7832
7833 // Fix up the NetworkCapabilities of any networks that have this network as underlying.
7834 if (newDefaultNetwork != null) {
7835 propagateUnderlyingNetworkCapabilities(newDefaultNetwork.network);
7836 }
7837
7838 // Set an app level managed default and return since further processing only applies to the
7839 // default network.
7840 if (mDefaultRequest != nri) {
7841 makeDefaultForApps(nri, oldDefaultNetwork, newDefaultNetwork);
7842 return;
7843 }
7844
7845 makeDefaultNetwork(newDefaultNetwork);
7846
7847 if (oldDefaultNetwork != null) {
7848 mLingerMonitor.noteLingerDefaultNetwork(oldDefaultNetwork, newDefaultNetwork);
7849 }
7850 mNetworkActivityTracker.updateDataActivityTracking(newDefaultNetwork, oldDefaultNetwork);
7851 handleApplyDefaultProxy(null != newDefaultNetwork
7852 ? newDefaultNetwork.linkProperties.getHttpProxy() : null);
7853 updateTcpBufferSizes(null != newDefaultNetwork
7854 ? newDefaultNetwork.linkProperties.getTcpBufferSizes() : null);
7855 notifyIfacesChangedForNetworkStats();
7856 }
7857
7858 private void makeDefaultForApps(@NonNull final NetworkRequestInfo nri,
7859 @Nullable final NetworkAgentInfo oldDefaultNetwork,
7860 @Nullable final NetworkAgentInfo newDefaultNetwork) {
7861 try {
7862 if (VDBG) {
7863 log("Setting default network for " + nri
7864 + " using UIDs " + nri.getUids()
7865 + " with old network " + (oldDefaultNetwork != null
7866 ? oldDefaultNetwork.network().getNetId() : "null")
7867 + " and new network " + (newDefaultNetwork != null
7868 ? newDefaultNetwork.network().getNetId() : "null"));
7869 }
7870 if (nri.getUids().isEmpty()) {
7871 throw new IllegalStateException("makeDefaultForApps called without specifying"
7872 + " any applications to set as the default." + nri);
7873 }
7874 if (null != newDefaultNetwork) {
paulhude2a2392021-06-09 16:11:35 +08007875 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00007876 newDefaultNetwork.network.getNetId(),
paulhude2a2392021-06-09 16:11:35 +08007877 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08007878 nri.getPreferenceOrderForNetd()));
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00007879 }
7880 if (null != oldDefaultNetwork) {
paulhude2a2392021-06-09 16:11:35 +08007881 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00007882 oldDefaultNetwork.network.getNetId(),
paulhude2a2392021-06-09 16:11:35 +08007883 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08007884 nri.getPreferenceOrderForNetd()));
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00007885 }
7886 } catch (RemoteException | ServiceSpecificException e) {
7887 loge("Exception setting app default network", e);
7888 }
7889 }
7890
7891 private void makeDefaultNetwork(@Nullable final NetworkAgentInfo newDefaultNetwork) {
7892 try {
7893 if (null != newDefaultNetwork) {
7894 mNetd.networkSetDefault(newDefaultNetwork.network.getNetId());
7895 } else {
7896 mNetd.networkClearDefault();
7897 }
7898 } catch (RemoteException | ServiceSpecificException e) {
7899 loge("Exception setting default network :" + e);
7900 }
7901 }
7902
7903 private void processListenRequests(@NonNull final NetworkAgentInfo nai) {
7904 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
7905 processNewlyLostListenRequests(nai);
7906 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
7907 processNewlySatisfiedListenRequests(nai);
7908 }
7909
7910 private void processNewlyLostListenRequests(@NonNull final NetworkAgentInfo nai) {
7911 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
7912 if (nri.isMultilayerRequest()) {
7913 continue;
7914 }
7915 final NetworkRequest nr = nri.mRequests.get(0);
7916 if (!nr.isListen()) continue;
7917 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
7918 nai.removeRequest(nr.requestId);
7919 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
7920 }
7921 }
7922 }
7923
7924 private void processNewlySatisfiedListenRequests(@NonNull final NetworkAgentInfo nai) {
7925 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
7926 if (nri.isMultilayerRequest()) {
7927 continue;
7928 }
7929 final NetworkRequest nr = nri.mRequests.get(0);
7930 if (!nr.isListen()) continue;
7931 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
7932 nai.addRequest(nr);
7933 notifyNetworkAvailable(nai, nri);
7934 }
7935 }
7936 }
7937
7938 // An accumulator class to gather the list of changes that result from a rematch.
7939 private static class NetworkReassignment {
7940 static class RequestReassignment {
7941 @NonNull public final NetworkRequestInfo mNetworkRequestInfo;
7942 @Nullable public final NetworkRequest mOldNetworkRequest;
7943 @Nullable public final NetworkRequest mNewNetworkRequest;
7944 @Nullable public final NetworkAgentInfo mOldNetwork;
7945 @Nullable public final NetworkAgentInfo mNewNetwork;
7946 RequestReassignment(@NonNull final NetworkRequestInfo networkRequestInfo,
7947 @Nullable final NetworkRequest oldNetworkRequest,
7948 @Nullable final NetworkRequest newNetworkRequest,
7949 @Nullable final NetworkAgentInfo oldNetwork,
7950 @Nullable final NetworkAgentInfo newNetwork) {
7951 mNetworkRequestInfo = networkRequestInfo;
7952 mOldNetworkRequest = oldNetworkRequest;
7953 mNewNetworkRequest = newNetworkRequest;
7954 mOldNetwork = oldNetwork;
7955 mNewNetwork = newNetwork;
7956 }
7957
7958 public String toString() {
7959 final NetworkRequest requestToShow = null != mNewNetworkRequest
7960 ? mNewNetworkRequest : mNetworkRequestInfo.mRequests.get(0);
7961 return requestToShow.requestId + " : "
7962 + (null != mOldNetwork ? mOldNetwork.network.getNetId() : "null")
7963 + " → " + (null != mNewNetwork ? mNewNetwork.network.getNetId() : "null");
7964 }
7965 }
7966
7967 @NonNull private final ArrayList<RequestReassignment> mReassignments = new ArrayList<>();
7968
7969 @NonNull Iterable<RequestReassignment> getRequestReassignments() {
7970 return mReassignments;
7971 }
7972
7973 void addRequestReassignment(@NonNull final RequestReassignment reassignment) {
7974 if (Build.isDebuggable()) {
7975 // The code is never supposed to add two reassignments of the same request. Make
7976 // sure this stays true, but without imposing this expensive check on all
7977 // reassignments on all user devices.
7978 for (final RequestReassignment existing : mReassignments) {
7979 if (existing.mNetworkRequestInfo.equals(reassignment.mNetworkRequestInfo)) {
7980 throw new IllegalStateException("Trying to reassign ["
7981 + reassignment + "] but already have ["
7982 + existing + "]");
7983 }
7984 }
7985 }
7986 mReassignments.add(reassignment);
7987 }
7988
7989 // Will return null if this reassignment does not change the network assigned to
7990 // the passed request.
7991 @Nullable
7992 private RequestReassignment getReassignment(@NonNull final NetworkRequestInfo nri) {
7993 for (final RequestReassignment event : getRequestReassignments()) {
7994 if (nri == event.mNetworkRequestInfo) return event;
7995 }
7996 return null;
7997 }
7998
7999 public String toString() {
8000 final StringJoiner sj = new StringJoiner(", " /* delimiter */,
8001 "NetReassign [" /* prefix */, "]" /* suffix */);
8002 if (mReassignments.isEmpty()) return sj.add("no changes").toString();
8003 for (final RequestReassignment rr : getRequestReassignments()) {
8004 sj.add(rr.toString());
8005 }
8006 return sj.toString();
8007 }
8008
8009 public String debugString() {
8010 final StringBuilder sb = new StringBuilder();
8011 sb.append("NetworkReassignment :");
8012 if (mReassignments.isEmpty()) return sb.append(" no changes").toString();
8013 for (final RequestReassignment rr : getRequestReassignments()) {
8014 sb.append("\n ").append(rr);
8015 }
8016 return sb.append("\n").toString();
8017 }
8018 }
8019
8020 private void updateSatisfiersForRematchRequest(@NonNull final NetworkRequestInfo nri,
8021 @Nullable final NetworkRequest previousRequest,
8022 @Nullable final NetworkRequest newRequest,
8023 @Nullable final NetworkAgentInfo previousSatisfier,
8024 @Nullable final NetworkAgentInfo newSatisfier,
8025 final long now) {
8026 if (null != newSatisfier && mNoServiceNetwork != newSatisfier) {
8027 if (VDBG) log("rematch for " + newSatisfier.toShortString());
8028 if (null != previousRequest && null != previousSatisfier) {
8029 if (VDBG || DDBG) {
8030 log(" accepting network in place of " + previousSatisfier.toShortString());
8031 }
8032 previousSatisfier.removeRequest(previousRequest.requestId);
8033 previousSatisfier.lingerRequest(previousRequest.requestId, now);
8034 } else {
8035 if (VDBG || DDBG) log(" accepting network in place of null");
8036 }
8037
8038 // To prevent constantly CPU wake up for nascent timer, if a network comes up
8039 // and immediately satisfies a request then remove the timer. This will happen for
8040 // all networks except in the case of an underlying network for a VCN.
8041 if (newSatisfier.isNascent()) {
8042 newSatisfier.unlingerRequest(NetworkRequest.REQUEST_ID_NONE);
8043 newSatisfier.unsetInactive();
8044 }
8045
8046 // if newSatisfier is not null, then newRequest may not be null.
8047 newSatisfier.unlingerRequest(newRequest.requestId);
8048 if (!newSatisfier.addRequest(newRequest)) {
8049 Log.wtf(TAG, "BUG: " + newSatisfier.toShortString() + " already has "
8050 + newRequest);
8051 }
8052 } else if (null != previousRequest && null != previousSatisfier) {
8053 if (DBG) {
8054 log("Network " + previousSatisfier.toShortString() + " stopped satisfying"
8055 + " request " + previousRequest.requestId);
8056 }
8057 previousSatisfier.removeRequest(previousRequest.requestId);
8058 }
8059 nri.setSatisfier(newSatisfier, newRequest);
8060 }
8061
8062 /**
8063 * This function is triggered when something can affect what network should satisfy what
8064 * request, and it computes the network reassignment from the passed collection of requests to
8065 * network match to the one that the system should now have. That data is encoded in an
8066 * object that is a list of changes, each of them having an NRI, and old satisfier, and a new
8067 * satisfier.
8068 *
8069 * After the reassignment is computed, it is applied to the state objects.
8070 *
8071 * @param networkRequests the nri objects to evaluate for possible network reassignment
8072 * @return NetworkReassignment listing of proposed network assignment changes
8073 */
8074 @NonNull
8075 private NetworkReassignment computeNetworkReassignment(
8076 @NonNull final Collection<NetworkRequestInfo> networkRequests) {
8077 final NetworkReassignment changes = new NetworkReassignment();
8078
8079 // Gather the list of all relevant agents.
8080 final ArrayList<NetworkAgentInfo> nais = new ArrayList<>();
8081 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
8082 if (!nai.everConnected) {
8083 continue;
8084 }
8085 nais.add(nai);
8086 }
8087
8088 for (final NetworkRequestInfo nri : networkRequests) {
8089 // Non-multilayer listen requests can be ignored.
8090 if (!nri.isMultilayerRequest() && nri.mRequests.get(0).isListen()) {
8091 continue;
8092 }
8093 NetworkAgentInfo bestNetwork = null;
8094 NetworkRequest bestRequest = null;
8095 for (final NetworkRequest req : nri.mRequests) {
8096 bestNetwork = mNetworkRanker.getBestNetwork(req, nais, nri.getSatisfier());
8097 // Stop evaluating as the highest possible priority request is satisfied.
8098 if (null != bestNetwork) {
8099 bestRequest = req;
8100 break;
8101 }
8102 }
8103 if (null == bestNetwork && isDefaultBlocked(nri)) {
8104 // Remove default networking if disallowed for managed default requests.
8105 bestNetwork = mNoServiceNetwork;
8106 }
8107 if (nri.getSatisfier() != bestNetwork) {
8108 // bestNetwork may be null if no network can satisfy this request.
8109 changes.addRequestReassignment(new NetworkReassignment.RequestReassignment(
8110 nri, nri.mActiveRequest, bestRequest, nri.getSatisfier(), bestNetwork));
8111 }
8112 }
8113 return changes;
8114 }
8115
8116 private Set<NetworkRequestInfo> getNrisFromGlobalRequests() {
8117 return new HashSet<>(mNetworkRequests.values());
8118 }
8119
8120 /**
8121 * Attempt to rematch all Networks with all NetworkRequests. This may result in Networks
8122 * being disconnected.
8123 */
8124 private void rematchAllNetworksAndRequests() {
8125 rematchNetworksAndRequests(getNrisFromGlobalRequests());
8126 }
8127
8128 /**
8129 * Attempt to rematch all Networks with given NetworkRequests. This may result in Networks
8130 * being disconnected.
8131 */
8132 private void rematchNetworksAndRequests(
8133 @NonNull final Set<NetworkRequestInfo> networkRequests) {
8134 ensureRunningOnConnectivityServiceThread();
8135 // TODO: This may be slow, and should be optimized.
8136 final long now = SystemClock.elapsedRealtime();
8137 final NetworkReassignment changes = computeNetworkReassignment(networkRequests);
8138 if (VDBG || DDBG) {
8139 log(changes.debugString());
8140 } else if (DBG) {
8141 log(changes.toString()); // Shorter form, only one line of log
8142 }
8143 applyNetworkReassignment(changes, now);
8144 issueNetworkNeeds();
8145 }
8146
8147 private void applyNetworkReassignment(@NonNull final NetworkReassignment changes,
8148 final long now) {
8149 final Collection<NetworkAgentInfo> nais = mNetworkAgentInfos;
8150
8151 // Since most of the time there are only 0 or 1 background networks, it would probably
8152 // be more efficient to just use an ArrayList here. TODO : measure performance
8153 final ArraySet<NetworkAgentInfo> oldBgNetworks = new ArraySet<>();
8154 for (final NetworkAgentInfo nai : nais) {
8155 if (nai.isBackgroundNetwork()) oldBgNetworks.add(nai);
8156 }
8157
8158 // First, update the lists of satisfied requests in the network agents. This is necessary
8159 // because some code later depends on this state to be correct, most prominently computing
8160 // the linger status.
8161 for (final NetworkReassignment.RequestReassignment event :
8162 changes.getRequestReassignments()) {
8163 updateSatisfiersForRematchRequest(event.mNetworkRequestInfo,
8164 event.mOldNetworkRequest, event.mNewNetworkRequest,
8165 event.mOldNetwork, event.mNewNetwork,
8166 now);
8167 }
8168
8169 // Process default network changes if applicable.
8170 processDefaultNetworkChanges(changes);
8171
8172 // Notify requested networks are available after the default net is switched, but
8173 // before LegacyTypeTracker sends legacy broadcasts
8174 for (final NetworkReassignment.RequestReassignment event :
8175 changes.getRequestReassignments()) {
8176 if (null != event.mNewNetwork) {
8177 notifyNetworkAvailable(event.mNewNetwork, event.mNetworkRequestInfo);
8178 } else {
8179 callCallbackForRequest(event.mNetworkRequestInfo, event.mOldNetwork,
8180 ConnectivityManager.CALLBACK_LOST, 0);
8181 }
8182 }
8183
8184 // Update the inactivity state before processing listen callbacks, because the background
8185 // computation depends on whether the network is inactive. Don't send the LOSING callbacks
8186 // just yet though, because they have to be sent after the listens are processed to keep
8187 // backward compatibility.
8188 final ArrayList<NetworkAgentInfo> inactiveNetworks = new ArrayList<>();
8189 for (final NetworkAgentInfo nai : nais) {
8190 // Rematching may have altered the inactivity state of some networks, so update all
8191 // inactivity timers. updateInactivityState reads the state from the network agent
8192 // and does nothing if the state has not changed : the source of truth is controlled
8193 // with NetworkAgentInfo#lingerRequest and NetworkAgentInfo#unlingerRequest, which
8194 // have been called while rematching the individual networks above.
8195 if (updateInactivityState(nai, now)) {
8196 inactiveNetworks.add(nai);
8197 }
8198 }
8199
8200 for (final NetworkAgentInfo nai : nais) {
8201 if (!nai.everConnected) continue;
8202 final boolean oldBackground = oldBgNetworks.contains(nai);
8203 // Process listen requests and update capabilities if the background state has
8204 // changed for this network. For consistency with previous behavior, send onLost
8205 // callbacks before onAvailable.
8206 processNewlyLostListenRequests(nai);
8207 if (oldBackground != nai.isBackgroundNetwork()) {
8208 applyBackgroundChangeForRematch(nai);
8209 }
8210 processNewlySatisfiedListenRequests(nai);
8211 }
8212
8213 for (final NetworkAgentInfo nai : inactiveNetworks) {
8214 // For nascent networks, if connecting with no foreground request, skip broadcasting
8215 // LOSING for backward compatibility. This is typical when mobile data connected while
8216 // wifi connected with mobile data always-on enabled.
8217 if (nai.isNascent()) continue;
8218 notifyNetworkLosing(nai, now);
8219 }
8220
8221 updateLegacyTypeTrackerAndVpnLockdownForRematch(changes, nais);
8222
8223 // Tear down all unneeded networks.
8224 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
8225 if (unneeded(nai, UnneededFor.TEARDOWN)) {
8226 if (nai.getInactivityExpiry() > 0) {
8227 // This network has active linger timers and no requests, but is not
8228 // lingering. Linger it.
8229 //
8230 // One way (the only way?) this can happen if this network is unvalidated
8231 // and became unneeded due to another network improving its score to the
8232 // point where this network will no longer be able to satisfy any requests
8233 // even if it validates.
8234 if (updateInactivityState(nai, now)) {
8235 notifyNetworkLosing(nai, now);
8236 }
8237 } else {
8238 if (DBG) log("Reaping " + nai.toShortString());
8239 teardownUnneededNetwork(nai);
8240 }
8241 }
8242 }
8243 }
8244
8245 /**
8246 * Apply a change in background state resulting from rematching networks with requests.
8247 *
8248 * During rematch, a network may change background states by starting to satisfy or stopping
8249 * to satisfy a foreground request. Listens don't count for this. When a network changes
8250 * background states, its capabilities need to be updated and callbacks fired for the
8251 * capability change.
8252 *
8253 * @param nai The network that changed background states
8254 */
8255 private void applyBackgroundChangeForRematch(@NonNull final NetworkAgentInfo nai) {
8256 final NetworkCapabilities newNc = mixInCapabilities(nai, nai.networkCapabilities);
8257 if (Objects.equals(nai.networkCapabilities, newNc)) return;
8258 updateNetworkPermissions(nai, newNc);
8259 nai.getAndSetNetworkCapabilities(newNc);
8260 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
8261 }
8262
8263 private void updateLegacyTypeTrackerAndVpnLockdownForRematch(
8264 @NonNull final NetworkReassignment changes,
8265 @NonNull final Collection<NetworkAgentInfo> nais) {
8266 final NetworkReassignment.RequestReassignment reassignmentOfDefault =
8267 changes.getReassignment(mDefaultRequest);
8268 final NetworkAgentInfo oldDefaultNetwork =
8269 null != reassignmentOfDefault ? reassignmentOfDefault.mOldNetwork : null;
8270 final NetworkAgentInfo newDefaultNetwork =
8271 null != reassignmentOfDefault ? reassignmentOfDefault.mNewNetwork : null;
8272
8273 if (oldDefaultNetwork != newDefaultNetwork) {
8274 // Maintain the illusion : since the legacy API only understands one network at a time,
8275 // if the default network changed, apps should see a disconnected broadcast for the
8276 // old default network before they see a connected broadcast for the new one.
8277 if (oldDefaultNetwork != null) {
8278 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
8279 oldDefaultNetwork, true);
8280 }
8281 if (newDefaultNetwork != null) {
8282 // The new default network can be newly null if and only if the old default
8283 // network doesn't satisfy the default request any more because it lost a
8284 // capability.
8285 mDefaultInetConditionPublished = newDefaultNetwork.lastValidated ? 100 : 0;
8286 mLegacyTypeTracker.add(
8287 newDefaultNetwork.networkInfo.getType(), newDefaultNetwork);
8288 }
8289 }
8290
8291 // Now that all the callbacks have been sent, send the legacy network broadcasts
8292 // as needed. This is necessary so that legacy requests correctly bind dns
8293 // requests to this network. The legacy users are listening for this broadcast
8294 // and will generally do a dns request so they can ensureRouteToHost and if
8295 // they do that before the callbacks happen they'll use the default network.
8296 //
8297 // TODO: Is there still a race here? The legacy broadcast will be sent after sending
8298 // callbacks, but if apps can receive the broadcast before the callback, they still might
8299 // have an inconsistent view of networking.
8300 //
8301 // This *does* introduce a race where if the user uses the new api
8302 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
8303 // they may get old info. Reverse this after the old startUsing api is removed.
8304 // This is on top of the multiple intent sequencing referenced in the todo above.
8305 for (NetworkAgentInfo nai : nais) {
8306 if (nai.everConnected) {
8307 addNetworkToLegacyTypeTracker(nai);
8308 }
8309 }
8310 }
8311
8312 private void issueNetworkNeeds() {
8313 ensureRunningOnConnectivityServiceThread();
8314 for (final NetworkOfferInfo noi : mNetworkOffers) {
8315 issueNetworkNeeds(noi);
8316 }
8317 }
8318
8319 private void issueNetworkNeeds(@NonNull final NetworkOfferInfo noi) {
8320 ensureRunningOnConnectivityServiceThread();
8321 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
8322 informOffer(nri, noi.offer, mNetworkRanker);
8323 }
8324 }
8325
8326 /**
8327 * Inform a NetworkOffer about any new situation of a request.
8328 *
8329 * This function handles updates to offers. A number of events may happen that require
8330 * updating the registrant for this offer about the situation :
8331 * • The offer itself was updated. This may lead the offer to no longer being able
8332 * to satisfy a request or beat a satisfier (and therefore be no longer needed),
8333 * or conversely being strengthened enough to beat the satisfier (and therefore
8334 * start being needed)
8335 * • The network satisfying a request changed (including cases where the request
8336 * starts or stops being satisfied). The new network may be a stronger or weaker
8337 * match than the old one, possibly affecting whether the offer is needed.
8338 * • The network satisfying a request updated their score. This may lead the offer
8339 * to no longer be able to beat it if the current satisfier got better, or
8340 * conversely start being a good choice if the current satisfier got weaker.
8341 *
8342 * @param nri The request
8343 * @param offer The offer. This may be an updated offer.
8344 */
8345 private static void informOffer(@NonNull NetworkRequestInfo nri,
8346 @NonNull final NetworkOffer offer, @NonNull final NetworkRanker networkRanker) {
8347 final NetworkRequest activeRequest = nri.isBeingSatisfied() ? nri.getActiveRequest() : null;
8348 final NetworkAgentInfo satisfier = null != activeRequest ? nri.getSatisfier() : null;
8349
8350 // Multi-layer requests have a currently active request, the one being satisfied.
8351 // Since the system will try to bring up a better network than is currently satisfying
8352 // the request, NetworkProviders need to be told the offers matching the requests *above*
8353 // the currently satisfied one are needed, that the ones *below* the satisfied one are
8354 // not needed, and the offer is needed for the active request iff the offer can beat
8355 // the satisfier.
8356 // For non-multilayer requests, the logic above gracefully degenerates to only the
8357 // last case.
8358 // To achieve this, the loop below will proceed in three steps. In a first phase, inform
8359 // providers that the offer is needed for this request, until the active request is found.
8360 // In a second phase, deal with the currently active request. In a third phase, inform
8361 // the providers that offer is unneeded for the remaining requests.
8362
8363 // First phase : inform providers of all requests above the active request.
8364 int i;
8365 for (i = 0; nri.mRequests.size() > i; ++i) {
8366 final NetworkRequest request = nri.mRequests.get(i);
8367 if (activeRequest == request) break; // Found the active request : go to phase 2
8368 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
8369 // Since this request is higher-priority than the one currently satisfied, if the
8370 // offer can satisfy it, the provider should try and bring up the network for sure ;
8371 // no need to even ask the ranker – an offer that can satisfy is always better than
8372 // no network. Hence tell the provider so unless it already knew.
8373 if (request.canBeSatisfiedBy(offer.caps) && !offer.neededFor(request)) {
8374 offer.onNetworkNeeded(request);
8375 }
8376 }
8377
8378 // Second phase : deal with the active request (if any)
8379 if (null != activeRequest && activeRequest.isRequest()) {
8380 final boolean oldNeeded = offer.neededFor(activeRequest);
Junyu Laidc3a7a32021-05-26 12:23:56 +00008381 // If an offer can satisfy the request, it is considered needed if it is currently
8382 // served by this provider or if this offer can beat the current satisfier.
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00008383 final boolean currentlyServing = satisfier != null
Junyu Laidc3a7a32021-05-26 12:23:56 +00008384 && satisfier.factorySerialNumber == offer.providerId
8385 && activeRequest.canBeSatisfiedBy(offer.caps);
8386 final boolean newNeeded = currentlyServing
8387 || networkRanker.mightBeat(activeRequest, satisfier, offer);
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00008388 if (newNeeded != oldNeeded) {
8389 if (newNeeded) {
8390 offer.onNetworkNeeded(activeRequest);
8391 } else {
8392 // The offer used to be able to beat the satisfier. Now it can't.
8393 offer.onNetworkUnneeded(activeRequest);
8394 }
8395 }
8396 }
8397
8398 // Third phase : inform the providers that the offer isn't needed for any request
8399 // below the active one.
8400 for (++i /* skip the active request */; nri.mRequests.size() > i; ++i) {
8401 final NetworkRequest request = nri.mRequests.get(i);
8402 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
8403 // Since this request is lower-priority than the one currently satisfied, if the
8404 // offer can satisfy it, the provider should not try and bring up the network.
8405 // Hence tell the provider so unless it already knew.
8406 if (offer.neededFor(request)) {
8407 offer.onNetworkUnneeded(request);
8408 }
8409 }
8410 }
8411
8412 private void addNetworkToLegacyTypeTracker(@NonNull final NetworkAgentInfo nai) {
8413 for (int i = 0; i < nai.numNetworkRequests(); i++) {
8414 NetworkRequest nr = nai.requestAt(i);
8415 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
8416 // legacy type tracker filters out repeat adds
8417 mLegacyTypeTracker.add(nr.legacyType, nai);
8418 }
8419 }
8420
8421 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
8422 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
8423 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
8424 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
8425 if (nai.isVPN()) {
8426 mLegacyTypeTracker.add(TYPE_VPN, nai);
8427 }
8428 }
8429
8430 private void updateInetCondition(NetworkAgentInfo nai) {
8431 // Don't bother updating until we've graduated to validated at least once.
8432 if (!nai.everValidated) return;
8433 // For now only update icons for the default connection.
8434 // TODO: Update WiFi and cellular icons separately. b/17237507
8435 if (!isDefaultNetwork(nai)) return;
8436
8437 int newInetCondition = nai.lastValidated ? 100 : 0;
8438 // Don't repeat publish.
8439 if (newInetCondition == mDefaultInetConditionPublished) return;
8440
8441 mDefaultInetConditionPublished = newInetCondition;
8442 sendInetConditionBroadcast(nai.networkInfo);
8443 }
8444
8445 @NonNull
8446 private NetworkInfo mixInInfo(@NonNull final NetworkAgentInfo nai, @NonNull NetworkInfo info) {
8447 final NetworkInfo newInfo = new NetworkInfo(info);
8448 // The suspended and roaming bits are managed in NetworkCapabilities.
8449 final boolean suspended =
8450 !nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
8451 if (suspended && info.getDetailedState() == NetworkInfo.DetailedState.CONNECTED) {
8452 // Only override the state with SUSPENDED if the network is currently in CONNECTED
8453 // state. This is because the network could have been suspended before connecting,
8454 // or it could be disconnecting while being suspended, and in both these cases
8455 // the state should not be overridden. Note that the only detailed state that
8456 // maps to State.CONNECTED is DetailedState.CONNECTED, so there is also no need to
8457 // worry about multiple different substates of CONNECTED.
8458 newInfo.setDetailedState(NetworkInfo.DetailedState.SUSPENDED, info.getReason(),
8459 info.getExtraInfo());
8460 } else if (!suspended && info.getDetailedState() == NetworkInfo.DetailedState.SUSPENDED) {
8461 // SUSPENDED state is currently only overridden from CONNECTED state. In the case the
8462 // network agent is created, then goes to suspended, then goes out of suspended without
8463 // ever setting connected. Check if network agent is ever connected to update the state.
8464 newInfo.setDetailedState(nai.everConnected
8465 ? NetworkInfo.DetailedState.CONNECTED
8466 : NetworkInfo.DetailedState.CONNECTING,
8467 info.getReason(),
8468 info.getExtraInfo());
8469 }
8470 newInfo.setRoaming(!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_ROAMING));
8471 return newInfo;
8472 }
8473
8474 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo info) {
8475 final NetworkInfo newInfo = mixInInfo(networkAgent, info);
8476
8477 final NetworkInfo.State state = newInfo.getState();
8478 NetworkInfo oldInfo = null;
8479 synchronized (networkAgent) {
8480 oldInfo = networkAgent.networkInfo;
8481 networkAgent.networkInfo = newInfo;
8482 }
8483
8484 if (DBG) {
8485 log(networkAgent.toShortString() + " EVENT_NETWORK_INFO_CHANGED, going from "
8486 + oldInfo.getState() + " to " + state);
8487 }
8488
8489 if (!networkAgent.created
8490 && (state == NetworkInfo.State.CONNECTED
8491 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
8492
8493 // A network that has just connected has zero requests and is thus a foreground network.
8494 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
8495
8496 if (!createNativeNetwork(networkAgent)) return;
Lorenzo Colittibd079452021-07-02 11:47:57 +09008497 if (networkAgent.propagateUnderlyingCapabilities()) {
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00008498 // Initialize the network's capabilities to their starting values according to the
8499 // underlying networks. This ensures that the capabilities are correct before
8500 // anything happens to the network.
8501 updateCapabilitiesForNetwork(networkAgent);
8502 }
8503 networkAgent.created = true;
8504 networkAgent.onNetworkCreated();
8505 }
8506
8507 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
8508 networkAgent.everConnected = true;
8509
8510 // NetworkCapabilities need to be set before sending the private DNS config to
8511 // NetworkMonitor, otherwise NetworkMonitor cannot determine if validation is required.
8512 networkAgent.getAndSetNetworkCapabilities(networkAgent.networkCapabilities);
8513
8514 handlePerNetworkPrivateDnsConfig(networkAgent, mDnsManager.getPrivateDnsConfig());
8515 updateLinkProperties(networkAgent, new LinkProperties(networkAgent.linkProperties),
8516 null);
8517
8518 // Until parceled LinkProperties are sent directly to NetworkMonitor, the connect
8519 // command must be sent after updating LinkProperties to maximize chances of
8520 // NetworkMonitor seeing the correct LinkProperties when starting.
8521 // TODO: pass LinkProperties to the NetworkMonitor in the notifyNetworkConnected call.
8522 if (networkAgent.networkAgentConfig.acceptPartialConnectivity) {
8523 networkAgent.networkMonitor().setAcceptPartialConnectivity();
8524 }
8525 networkAgent.networkMonitor().notifyNetworkConnected(
8526 new LinkProperties(networkAgent.linkProperties,
8527 true /* parcelSensitiveFields */),
8528 networkAgent.networkCapabilities);
8529 scheduleUnvalidatedPrompt(networkAgent);
8530
8531 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
8532 // be communicated to a particular NetworkAgent depends only on the network's immutable,
8533 // capabilities, so it only needs to be done once on initial connect, not every time the
8534 // network's capabilities change. Note that we do this before rematching the network,
8535 // so we could decide to tear it down immediately afterwards. That's fine though - on
8536 // disconnection NetworkAgents should stop any signal strength monitoring they have been
8537 // doing.
8538 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
8539
8540 // Before first rematching networks, put an inactivity timer without any request, this
8541 // allows {@code updateInactivityState} to update the state accordingly and prevent
8542 // tearing down for any {@code unneeded} evaluation in this period.
8543 // Note that the timer will not be rescheduled since the expiry time is
8544 // fixed after connection regardless of the network satisfying other requests or not.
8545 // But it will be removed as soon as the network satisfies a request for the first time.
8546 networkAgent.lingerRequest(NetworkRequest.REQUEST_ID_NONE,
8547 SystemClock.elapsedRealtime(), mNascentDelayMs);
8548 networkAgent.setInactive();
8549
8550 // Consider network even though it is not yet validated.
8551 rematchAllNetworksAndRequests();
8552
8553 // This has to happen after matching the requests, because callbacks are just requests.
8554 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
8555 } else if (state == NetworkInfo.State.DISCONNECTED) {
8556 networkAgent.disconnect();
8557 if (networkAgent.isVPN()) {
8558 updateUids(networkAgent, networkAgent.networkCapabilities, null);
8559 }
8560 disconnectAndDestroyNetwork(networkAgent);
8561 if (networkAgent.isVPN()) {
8562 // As the active or bound network changes for apps, broadcast the default proxy, as
8563 // apps may need to update their proxy data. This is called after disconnecting from
8564 // VPN to make sure we do not broadcast the old proxy data.
8565 // TODO(b/122649188): send the broadcast only to VPN users.
8566 mProxyTracker.sendProxyBroadcast();
8567 }
8568 } else if (networkAgent.created && (oldInfo.getState() == NetworkInfo.State.SUSPENDED ||
8569 state == NetworkInfo.State.SUSPENDED)) {
8570 mLegacyTypeTracker.update(networkAgent);
8571 }
8572 }
8573
8574 private void updateNetworkScore(@NonNull final NetworkAgentInfo nai, final NetworkScore score) {
8575 if (VDBG || DDBG) log("updateNetworkScore for " + nai.toShortString() + " to " + score);
8576 nai.setScore(score);
8577 rematchAllNetworksAndRequests();
8578 }
8579
8580 // Notify only this one new request of the current state. Transfer all the
8581 // current state by calling NetworkCapabilities and LinkProperties callbacks
8582 // so that callers can be guaranteed to have as close to atomicity in state
8583 // transfer as can be supported by this current API.
8584 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
8585 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
8586 if (nri.mPendingIntent != null) {
8587 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
8588 // Attempt no subsequent state pushes where intents are involved.
8589 return;
8590 }
8591
8592 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
8593 final boolean metered = nai.networkCapabilities.isMetered();
8594 final boolean vpnBlocked = isUidBlockedByVpn(nri.mAsUid, mVpnBlockedUidRanges);
8595 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE,
8596 getBlockedState(blockedReasons, metered, vpnBlocked));
8597 }
8598
8599 // Notify the requests on this NAI that the network is now lingered.
8600 private void notifyNetworkLosing(@NonNull final NetworkAgentInfo nai, final long now) {
8601 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
8602 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
8603 }
8604
8605 private static int getBlockedState(int reasons, boolean metered, boolean vpnBlocked) {
8606 if (!metered) reasons &= ~BLOCKED_METERED_REASON_MASK;
8607 return vpnBlocked
8608 ? reasons | BLOCKED_REASON_LOCKDOWN_VPN
8609 : reasons & ~BLOCKED_REASON_LOCKDOWN_VPN;
8610 }
8611
8612 private void setUidBlockedReasons(int uid, @BlockedReason int blockedReasons) {
8613 if (blockedReasons == BLOCKED_REASON_NONE) {
8614 mUidBlockedReasons.delete(uid);
8615 } else {
8616 mUidBlockedReasons.put(uid, blockedReasons);
8617 }
8618 }
8619
8620 /**
8621 * Notify of the blocked state apps with a registered callback matching a given NAI.
8622 *
8623 * Unlike other callbacks, blocked status is different between each individual uid. So for
8624 * any given nai, all requests need to be considered according to the uid who filed it.
8625 *
8626 * @param nai The target NetworkAgentInfo.
8627 * @param oldMetered True if the previous network capabilities were metered.
8628 * @param newMetered True if the current network capabilities are metered.
8629 * @param oldBlockedUidRanges list of UID ranges previously blocked by lockdown VPN.
8630 * @param newBlockedUidRanges list of UID ranges blocked by lockdown VPN.
8631 */
8632 private void maybeNotifyNetworkBlocked(NetworkAgentInfo nai, boolean oldMetered,
8633 boolean newMetered, List<UidRange> oldBlockedUidRanges,
8634 List<UidRange> newBlockedUidRanges) {
8635
8636 for (int i = 0; i < nai.numNetworkRequests(); i++) {
8637 NetworkRequest nr = nai.requestAt(i);
8638 NetworkRequestInfo nri = mNetworkRequests.get(nr);
8639
8640 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
8641 final boolean oldVpnBlocked = isUidBlockedByVpn(nri.mAsUid, oldBlockedUidRanges);
8642 final boolean newVpnBlocked = (oldBlockedUidRanges != newBlockedUidRanges)
8643 ? isUidBlockedByVpn(nri.mAsUid, newBlockedUidRanges)
8644 : oldVpnBlocked;
8645
8646 final int oldBlockedState = getBlockedState(blockedReasons, oldMetered, oldVpnBlocked);
8647 final int newBlockedState = getBlockedState(blockedReasons, newMetered, newVpnBlocked);
8648 if (oldBlockedState != newBlockedState) {
8649 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
8650 newBlockedState);
8651 }
8652 }
8653 }
8654
8655 /**
8656 * Notify apps with a given UID of the new blocked state according to new uid state.
8657 * @param uid The uid for which the rules changed.
8658 * @param blockedReasons The reasons for why an uid is blocked.
8659 */
8660 private void maybeNotifyNetworkBlockedForNewState(int uid, @BlockedReason int blockedReasons) {
8661 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
8662 final boolean metered = nai.networkCapabilities.isMetered();
8663 final boolean vpnBlocked = isUidBlockedByVpn(uid, mVpnBlockedUidRanges);
8664
8665 final int oldBlockedState = getBlockedState(
8666 mUidBlockedReasons.get(uid, BLOCKED_REASON_NONE), metered, vpnBlocked);
8667 final int newBlockedState = getBlockedState(blockedReasons, metered, vpnBlocked);
8668 if (oldBlockedState == newBlockedState) {
8669 continue;
8670 }
8671 for (int i = 0; i < nai.numNetworkRequests(); i++) {
8672 NetworkRequest nr = nai.requestAt(i);
8673 NetworkRequestInfo nri = mNetworkRequests.get(nr);
8674 if (nri != null && nri.mAsUid == uid) {
8675 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
8676 newBlockedState);
8677 }
8678 }
8679 }
8680 }
8681
8682 @VisibleForTesting
8683 protected void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
8684 // The NetworkInfo we actually send out has no bearing on the real
8685 // state of affairs. For example, if the default connection is mobile,
8686 // and a request for HIPRI has just gone away, we need to pretend that
8687 // HIPRI has just disconnected. So we need to set the type to HIPRI and
8688 // the state to DISCONNECTED, even though the network is of type MOBILE
8689 // and is still connected.
8690 NetworkInfo info = new NetworkInfo(nai.networkInfo);
8691 info.setType(type);
8692 filterForLegacyLockdown(info);
8693 if (state != DetailedState.DISCONNECTED) {
8694 info.setDetailedState(state, null, info.getExtraInfo());
8695 sendConnectedBroadcast(info);
8696 } else {
8697 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
8698 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
8699 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
8700 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
8701 if (info.isFailover()) {
8702 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
8703 nai.networkInfo.setFailover(false);
8704 }
8705 if (info.getReason() != null) {
8706 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
8707 }
8708 if (info.getExtraInfo() != null) {
8709 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
8710 }
8711 NetworkAgentInfo newDefaultAgent = null;
8712 if (nai.isSatisfyingRequest(mDefaultRequest.mRequests.get(0).requestId)) {
8713 newDefaultAgent = mDefaultRequest.getSatisfier();
8714 if (newDefaultAgent != null) {
8715 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
8716 newDefaultAgent.networkInfo);
8717 } else {
8718 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
8719 }
8720 }
8721 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
8722 mDefaultInetConditionPublished);
8723 sendStickyBroadcast(intent);
8724 if (newDefaultAgent != null) {
8725 sendConnectedBroadcast(newDefaultAgent.networkInfo);
8726 }
8727 }
8728 }
8729
8730 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
8731 if (VDBG || DDBG) {
8732 String notification = ConnectivityManager.getCallbackName(notifyType);
8733 log("notifyType " + notification + " for " + networkAgent.toShortString());
8734 }
8735 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
8736 NetworkRequest nr = networkAgent.requestAt(i);
8737 NetworkRequestInfo nri = mNetworkRequests.get(nr);
8738 if (VDBG) log(" sending notification for " + nr);
8739 if (nri.mPendingIntent == null) {
8740 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
8741 } else {
8742 sendPendingIntentForRequest(nri, networkAgent, notifyType);
8743 }
8744 }
8745 }
8746
8747 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
8748 notifyNetworkCallbacks(networkAgent, notifyType, 0);
8749 }
8750
8751 /**
8752 * Returns the list of all interfaces that could be used by network traffic that does not
8753 * explicitly specify a network. This includes the default network, but also all VPNs that are
8754 * currently connected.
8755 *
8756 * Must be called on the handler thread.
8757 */
8758 @NonNull
8759 private ArrayList<Network> getDefaultNetworks() {
8760 ensureRunningOnConnectivityServiceThread();
8761 final ArrayList<Network> defaultNetworks = new ArrayList<>();
8762 final Set<Integer> activeNetIds = new ArraySet<>();
8763 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
8764 if (nri.isBeingSatisfied()) {
8765 activeNetIds.add(nri.getSatisfier().network().netId);
8766 }
8767 }
8768 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
8769 if (nai.everConnected && (activeNetIds.contains(nai.network().netId) || nai.isVPN())) {
8770 defaultNetworks.add(nai.network);
8771 }
8772 }
8773 return defaultNetworks;
8774 }
8775
8776 /**
8777 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
8778 * active iface's tracked properties has changed.
8779 */
8780 private void notifyIfacesChangedForNetworkStats() {
8781 ensureRunningOnConnectivityServiceThread();
8782 String activeIface = null;
8783 LinkProperties activeLinkProperties = getActiveLinkProperties();
8784 if (activeLinkProperties != null) {
8785 activeIface = activeLinkProperties.getInterfaceName();
8786 }
8787
8788 final UnderlyingNetworkInfo[] underlyingNetworkInfos = getAllVpnInfo();
8789 try {
8790 final ArrayList<NetworkStateSnapshot> snapshots = new ArrayList<>();
junyulai0f570222021-03-05 14:46:25 +08008791 for (final NetworkStateSnapshot snapshot : getAllNetworkStateSnapshots()) {
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00008792 snapshots.add(snapshot);
8793 }
8794 mStatsManager.notifyNetworkStatus(getDefaultNetworks(),
8795 snapshots, activeIface, Arrays.asList(underlyingNetworkInfos));
8796 } catch (Exception ignored) {
8797 }
8798 }
8799
8800 @Override
8801 public String getCaptivePortalServerUrl() {
8802 enforceNetworkStackOrSettingsPermission();
8803 String settingUrl = mResources.get().getString(
8804 R.string.config_networkCaptivePortalServerUrl);
8805
8806 if (!TextUtils.isEmpty(settingUrl)) {
8807 return settingUrl;
8808 }
8809
8810 settingUrl = Settings.Global.getString(mContext.getContentResolver(),
8811 ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL);
8812 if (!TextUtils.isEmpty(settingUrl)) {
8813 return settingUrl;
8814 }
8815
8816 return DEFAULT_CAPTIVE_PORTAL_HTTP_URL;
8817 }
8818
8819 @Override
8820 public void startNattKeepalive(Network network, int intervalSeconds,
8821 ISocketKeepaliveCallback cb, String srcAddr, int srcPort, String dstAddr) {
8822 enforceKeepalivePermission();
8823 mKeepaliveTracker.startNattKeepalive(
8824 getNetworkAgentInfoForNetwork(network), null /* fd */,
8825 intervalSeconds, cb,
8826 srcAddr, srcPort, dstAddr, NattSocketKeepalive.NATT_PORT);
8827 }
8828
8829 @Override
8830 public void startNattKeepaliveWithFd(Network network, ParcelFileDescriptor pfd, int resourceId,
8831 int intervalSeconds, ISocketKeepaliveCallback cb, String srcAddr,
8832 String dstAddr) {
8833 try {
8834 final FileDescriptor fd = pfd.getFileDescriptor();
8835 mKeepaliveTracker.startNattKeepalive(
8836 getNetworkAgentInfoForNetwork(network), fd, resourceId,
8837 intervalSeconds, cb,
8838 srcAddr, dstAddr, NattSocketKeepalive.NATT_PORT);
8839 } finally {
8840 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
8841 // startNattKeepalive calls Os.dup(fd) before returning, so we can close immediately.
8842 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
8843 IoUtils.closeQuietly(pfd);
8844 }
8845 }
8846 }
8847
8848 @Override
8849 public void startTcpKeepalive(Network network, ParcelFileDescriptor pfd, int intervalSeconds,
8850 ISocketKeepaliveCallback cb) {
8851 try {
8852 enforceKeepalivePermission();
8853 final FileDescriptor fd = pfd.getFileDescriptor();
8854 mKeepaliveTracker.startTcpKeepalive(
8855 getNetworkAgentInfoForNetwork(network), fd, intervalSeconds, cb);
8856 } finally {
8857 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
8858 // startTcpKeepalive calls Os.dup(fd) before returning, so we can close immediately.
8859 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
8860 IoUtils.closeQuietly(pfd);
8861 }
8862 }
8863 }
8864
8865 @Override
8866 public void stopKeepalive(Network network, int slot) {
8867 mHandler.sendMessage(mHandler.obtainMessage(
8868 NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE, slot, SocketKeepalive.SUCCESS, network));
8869 }
8870
8871 @Override
8872 public void factoryReset() {
8873 enforceSettingsPermission();
8874
Treehugger Robotfac2a722021-05-21 02:42:59 +00008875 final int uid = mDeps.getCallingUid();
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00008876 final long token = Binder.clearCallingIdentity();
8877 try {
Treehugger Robotfac2a722021-05-21 02:42:59 +00008878 if (mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_NETWORK_RESET,
8879 UserHandle.getUserHandleForUid(uid))) {
8880 return;
8881 }
8882
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00008883 final IpMemoryStore ipMemoryStore = IpMemoryStore.getMemoryStore(mContext);
8884 ipMemoryStore.factoryReset();
Treehugger Robotfac2a722021-05-21 02:42:59 +00008885
8886 // Turn airplane mode off
8887 setAirplaneMode(false);
8888
8889 // restore private DNS settings to default mode (opportunistic)
8890 if (!mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_CONFIG_PRIVATE_DNS,
8891 UserHandle.getUserHandleForUid(uid))) {
8892 ConnectivitySettingsManager.setPrivateDnsMode(mContext,
8893 PRIVATE_DNS_MODE_OPPORTUNISTIC);
8894 }
8895
8896 Settings.Global.putString(mContext.getContentResolver(),
8897 ConnectivitySettingsManager.NETWORK_AVOID_BAD_WIFI, null);
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00008898 } finally {
8899 Binder.restoreCallingIdentity(token);
8900 }
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00008901 }
8902
8903 @Override
8904 public byte[] getNetworkWatchlistConfigHash() {
8905 NetworkWatchlistManager nwm = mContext.getSystemService(NetworkWatchlistManager.class);
8906 if (nwm == null) {
8907 loge("Unable to get NetworkWatchlistManager");
8908 return null;
8909 }
8910 // Redirect it to network watchlist service to access watchlist file and calculate hash.
8911 return nwm.getWatchlistConfigHash();
8912 }
8913
8914 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
8915 int[] transports = nai.networkCapabilities.getTransportTypes();
8916 mMetricsLog.log(nai.network.getNetId(), transports, new NetworkEvent(evtype));
8917 }
8918
8919 private static boolean toBool(int encodedBoolean) {
8920 return encodedBoolean != 0; // Only 0 means false.
8921 }
8922
8923 private static int encodeBool(boolean b) {
8924 return b ? 1 : 0;
8925 }
8926
8927 @Override
8928 public int handleShellCommand(@NonNull ParcelFileDescriptor in,
8929 @NonNull ParcelFileDescriptor out, @NonNull ParcelFileDescriptor err,
8930 @NonNull String[] args) {
8931 return new ShellCmd().exec(this, in.getFileDescriptor(), out.getFileDescriptor(),
8932 err.getFileDescriptor(), args);
8933 }
8934
8935 private class ShellCmd extends BasicShellCommandHandler {
8936 @Override
8937 public int onCommand(String cmd) {
8938 if (cmd == null) {
8939 return handleDefaultCommands(cmd);
8940 }
8941 final PrintWriter pw = getOutPrintWriter();
8942 try {
8943 switch (cmd) {
8944 case "airplane-mode":
8945 final String action = getNextArg();
8946 if ("enable".equals(action)) {
8947 setAirplaneMode(true);
8948 return 0;
8949 } else if ("disable".equals(action)) {
8950 setAirplaneMode(false);
8951 return 0;
8952 } else if (action == null) {
8953 final ContentResolver cr = mContext.getContentResolver();
8954 final int enabled = Settings.Global.getInt(cr,
8955 Settings.Global.AIRPLANE_MODE_ON);
8956 pw.println(enabled == 0 ? "disabled" : "enabled");
8957 return 0;
8958 } else {
8959 onHelp();
8960 return -1;
8961 }
8962 default:
8963 return handleDefaultCommands(cmd);
8964 }
8965 } catch (Exception e) {
8966 pw.println(e);
8967 }
8968 return -1;
8969 }
8970
8971 @Override
8972 public void onHelp() {
8973 PrintWriter pw = getOutPrintWriter();
8974 pw.println("Connectivity service commands:");
8975 pw.println(" help");
8976 pw.println(" Print this help text.");
8977 pw.println(" airplane-mode [enable|disable]");
8978 pw.println(" Turn airplane mode on or off.");
8979 pw.println(" airplane-mode");
8980 pw.println(" Get airplane mode.");
8981 }
8982 }
8983
8984 private int getVpnType(@Nullable NetworkAgentInfo vpn) {
8985 if (vpn == null) return VpnManager.TYPE_VPN_NONE;
8986 final TransportInfo ti = vpn.networkCapabilities.getTransportInfo();
8987 if (!(ti instanceof VpnTransportInfo)) return VpnManager.TYPE_VPN_NONE;
8988 return ((VpnTransportInfo) ti).getType();
8989 }
8990
8991 /**
8992 * @param connectionInfo the connection to resolve.
8993 * @return {@code uid} if the connection is found and the app has permission to observe it
8994 * (e.g., if it is associated with the calling VPN app's tunnel) or {@code INVALID_UID} if the
8995 * connection is not found.
8996 */
8997 public int getConnectionOwnerUid(ConnectionInfo connectionInfo) {
8998 if (connectionInfo.protocol != IPPROTO_TCP && connectionInfo.protocol != IPPROTO_UDP) {
8999 throw new IllegalArgumentException("Unsupported protocol " + connectionInfo.protocol);
9000 }
9001
9002 final int uid = mDeps.getConnectionOwnerUid(connectionInfo.protocol,
9003 connectionInfo.local, connectionInfo.remote);
9004
9005 if (uid == INVALID_UID) return uid; // Not found.
9006
9007 // Connection owner UIDs are visible only to the network stack and to the VpnService-based
9008 // VPN, if any, that applies to the UID that owns the connection.
9009 if (checkNetworkStackPermission()) return uid;
9010
9011 final NetworkAgentInfo vpn = getVpnForUid(uid);
9012 if (vpn == null || getVpnType(vpn) != VpnManager.TYPE_VPN_SERVICE
9013 || vpn.networkCapabilities.getOwnerUid() != mDeps.getCallingUid()) {
9014 return INVALID_UID;
9015 }
9016
9017 return uid;
9018 }
9019
9020 /**
9021 * Returns a IBinder to a TestNetworkService. Will be lazily created as needed.
9022 *
9023 * <p>The TestNetworkService must be run in the system server due to TUN creation.
9024 */
9025 @Override
9026 public IBinder startOrGetTestNetworkService() {
9027 synchronized (mTNSLock) {
9028 TestNetworkService.enforceTestNetworkPermissions(mContext);
9029
9030 if (mTNS == null) {
9031 mTNS = new TestNetworkService(mContext);
9032 }
9033
9034 return mTNS;
9035 }
9036 }
9037
9038 /**
9039 * Handler used for managing all Connectivity Diagnostics related functions.
9040 *
9041 * @see android.net.ConnectivityDiagnosticsManager
9042 *
9043 * TODO(b/147816404): Explore moving ConnectivityDiagnosticsHandler to a separate file
9044 */
9045 @VisibleForTesting
9046 class ConnectivityDiagnosticsHandler extends Handler {
9047 private final String mTag = ConnectivityDiagnosticsHandler.class.getSimpleName();
9048
9049 /**
9050 * Used to handle ConnectivityDiagnosticsCallback registration events from {@link
9051 * android.net.ConnectivityDiagnosticsManager}.
9052 * obj = ConnectivityDiagnosticsCallbackInfo with IConnectivityDiagnosticsCallback and
9053 * NetworkRequestInfo to be registered
9054 */
9055 private static final int EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 1;
9056
9057 /**
9058 * Used to handle ConnectivityDiagnosticsCallback unregister events from {@link
9059 * android.net.ConnectivityDiagnosticsManager}.
9060 * obj = the IConnectivityDiagnosticsCallback to be unregistered
9061 * arg1 = the uid of the caller
9062 */
9063 private static final int EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 2;
9064
9065 /**
9066 * Event for {@link NetworkStateTrackerHandler} to trigger ConnectivityReport callbacks
9067 * after processing {@link #EVENT_NETWORK_TESTED} events.
9068 * obj = {@link ConnectivityReportEvent} representing ConnectivityReport info reported from
9069 * NetworkMonitor.
9070 * data = PersistableBundle of extras passed from NetworkMonitor.
9071 *
9072 * <p>See {@link ConnectivityService#EVENT_NETWORK_TESTED}.
9073 */
9074 private static final int EVENT_NETWORK_TESTED = ConnectivityService.EVENT_NETWORK_TESTED;
9075
9076 /**
9077 * Event for NetworkMonitor to inform ConnectivityService that a potential data stall has
9078 * been detected on the network.
9079 * obj = Long the timestamp (in millis) for when the suspected data stall was detected.
9080 * arg1 = {@link DataStallReport#DetectionMethod} indicating the detection method.
9081 * arg2 = NetID.
9082 * data = PersistableBundle of extras passed from NetworkMonitor.
9083 */
9084 private static final int EVENT_DATA_STALL_SUSPECTED = 4;
9085
9086 /**
9087 * Event for ConnectivityDiagnosticsHandler to handle network connectivity being reported to
9088 * the platform. This event will invoke {@link
9089 * IConnectivityDiagnosticsCallback#onNetworkConnectivityReported} for permissioned
9090 * callbacks.
Cody Kestingf1120be2020-08-03 18:01:40 -07009091 * obj = ReportedNetworkConnectivityInfo with info on reported Network connectivity.
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00009092 */
9093 private static final int EVENT_NETWORK_CONNECTIVITY_REPORTED = 5;
9094
9095 private ConnectivityDiagnosticsHandler(Looper looper) {
9096 super(looper);
9097 }
9098
9099 @Override
9100 public void handleMessage(Message msg) {
9101 switch (msg.what) {
9102 case EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
9103 handleRegisterConnectivityDiagnosticsCallback(
9104 (ConnectivityDiagnosticsCallbackInfo) msg.obj);
9105 break;
9106 }
9107 case EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
9108 handleUnregisterConnectivityDiagnosticsCallback(
9109 (IConnectivityDiagnosticsCallback) msg.obj, msg.arg1);
9110 break;
9111 }
9112 case EVENT_NETWORK_TESTED: {
9113 final ConnectivityReportEvent reportEvent =
9114 (ConnectivityReportEvent) msg.obj;
9115
9116 handleNetworkTestedWithExtras(reportEvent, reportEvent.mExtras);
9117 break;
9118 }
9119 case EVENT_DATA_STALL_SUSPECTED: {
9120 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
9121 final Pair<Long, PersistableBundle> arg =
9122 (Pair<Long, PersistableBundle>) msg.obj;
9123 if (nai == null) break;
9124
9125 handleDataStallSuspected(nai, arg.first, msg.arg1, arg.second);
9126 break;
9127 }
9128 case EVENT_NETWORK_CONNECTIVITY_REPORTED: {
Cody Kestingf1120be2020-08-03 18:01:40 -07009129 handleNetworkConnectivityReported((ReportedNetworkConnectivityInfo) msg.obj);
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00009130 break;
9131 }
9132 default: {
9133 Log.e(mTag, "Unrecognized event in ConnectivityDiagnostics: " + msg.what);
9134 }
9135 }
9136 }
9137 }
9138
9139 /** Class used for cleaning up IConnectivityDiagnosticsCallback instances after their death. */
9140 @VisibleForTesting
9141 class ConnectivityDiagnosticsCallbackInfo implements Binder.DeathRecipient {
9142 @NonNull private final IConnectivityDiagnosticsCallback mCb;
9143 @NonNull private final NetworkRequestInfo mRequestInfo;
9144 @NonNull private final String mCallingPackageName;
9145
9146 @VisibleForTesting
9147 ConnectivityDiagnosticsCallbackInfo(
9148 @NonNull IConnectivityDiagnosticsCallback cb,
9149 @NonNull NetworkRequestInfo nri,
9150 @NonNull String callingPackageName) {
9151 mCb = cb;
9152 mRequestInfo = nri;
9153 mCallingPackageName = callingPackageName;
9154 }
9155
9156 @Override
9157 public void binderDied() {
9158 log("ConnectivityDiagnosticsCallback IBinder died.");
9159 unregisterConnectivityDiagnosticsCallback(mCb);
9160 }
9161 }
9162
9163 /**
9164 * Class used for sending information from {@link
9165 * NetworkMonitorCallbacks#notifyNetworkTestedWithExtras} to the handler for processing it.
9166 */
9167 private static class NetworkTestedResults {
9168 private final int mNetId;
9169 private final int mTestResult;
9170 private final long mTimestampMillis;
9171 @Nullable private final String mRedirectUrl;
9172
9173 private NetworkTestedResults(
9174 int netId, int testResult, long timestampMillis, @Nullable String redirectUrl) {
9175 mNetId = netId;
9176 mTestResult = testResult;
9177 mTimestampMillis = timestampMillis;
9178 mRedirectUrl = redirectUrl;
9179 }
9180 }
9181
9182 /**
9183 * Class used for sending information from {@link NetworkStateTrackerHandler} to {@link
9184 * ConnectivityDiagnosticsHandler}.
9185 */
9186 private static class ConnectivityReportEvent {
9187 private final long mTimestampMillis;
9188 @NonNull private final NetworkAgentInfo mNai;
9189 private final PersistableBundle mExtras;
9190
9191 private ConnectivityReportEvent(long timestampMillis, @NonNull NetworkAgentInfo nai,
9192 PersistableBundle p) {
9193 mTimestampMillis = timestampMillis;
9194 mNai = nai;
9195 mExtras = p;
9196 }
9197 }
9198
Cody Kestingf1120be2020-08-03 18:01:40 -07009199 /**
9200 * Class used for sending info for a call to {@link #reportNetworkConnectivity()} to {@link
9201 * ConnectivityDiagnosticsHandler}.
9202 */
9203 private static class ReportedNetworkConnectivityInfo {
9204 public final boolean hasConnectivity;
9205 public final boolean isNetworkRevalidating;
9206 public final int reporterUid;
9207 @NonNull public final NetworkAgentInfo nai;
9208
9209 private ReportedNetworkConnectivityInfo(
9210 boolean hasConnectivity,
9211 boolean isNetworkRevalidating,
9212 int reporterUid,
9213 @NonNull NetworkAgentInfo nai) {
9214 this.hasConnectivity = hasConnectivity;
9215 this.isNetworkRevalidating = isNetworkRevalidating;
9216 this.reporterUid = reporterUid;
9217 this.nai = nai;
9218 }
9219 }
9220
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00009221 private void handleRegisterConnectivityDiagnosticsCallback(
9222 @NonNull ConnectivityDiagnosticsCallbackInfo cbInfo) {
9223 ensureRunningOnConnectivityServiceThread();
9224
9225 final IConnectivityDiagnosticsCallback cb = cbInfo.mCb;
9226 final IBinder iCb = cb.asBinder();
9227 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
9228
9229 // Connectivity Diagnostics are meant to be used with a single network request. It would be
9230 // confusing for these networks to change when an NRI is satisfied in another layer.
9231 if (nri.isMultilayerRequest()) {
9232 throw new IllegalArgumentException("Connectivity Diagnostics do not support multilayer "
9233 + "network requests.");
9234 }
9235
9236 // This means that the client registered the same callback multiple times. Do
9237 // not override the previous entry, and exit silently.
9238 if (mConnectivityDiagnosticsCallbacks.containsKey(iCb)) {
9239 if (VDBG) log("Diagnostics callback is already registered");
9240
9241 // Decrement the reference count for this NetworkRequestInfo. The reference count is
9242 // incremented when the NetworkRequestInfo is created as part of
9243 // enforceRequestCountLimit().
9244 nri.decrementRequestCount();
9245 return;
9246 }
9247
9248 mConnectivityDiagnosticsCallbacks.put(iCb, cbInfo);
9249
9250 try {
9251 iCb.linkToDeath(cbInfo, 0);
9252 } catch (RemoteException e) {
9253 cbInfo.binderDied();
9254 return;
9255 }
9256
9257 // Once registered, provide ConnectivityReports for matching Networks
9258 final List<NetworkAgentInfo> matchingNetworks = new ArrayList<>();
9259 synchronized (mNetworkForNetId) {
9260 for (int i = 0; i < mNetworkForNetId.size(); i++) {
9261 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
9262 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0)
9263 if (nai.satisfies(nri.mRequests.get(0))) {
9264 matchingNetworks.add(nai);
9265 }
9266 }
9267 }
9268 for (final NetworkAgentInfo nai : matchingNetworks) {
9269 final ConnectivityReport report = nai.getConnectivityReport();
9270 if (report == null) {
9271 continue;
9272 }
9273 if (!checkConnectivityDiagnosticsPermissions(
9274 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
9275 continue;
9276 }
9277
9278 try {
9279 cb.onConnectivityReportAvailable(report);
9280 } catch (RemoteException e) {
9281 // Exception while sending the ConnectivityReport. Move on to the next network.
9282 }
9283 }
9284 }
9285
9286 private void handleUnregisterConnectivityDiagnosticsCallback(
9287 @NonNull IConnectivityDiagnosticsCallback cb, int uid) {
9288 ensureRunningOnConnectivityServiceThread();
9289 final IBinder iCb = cb.asBinder();
9290
9291 final ConnectivityDiagnosticsCallbackInfo cbInfo =
9292 mConnectivityDiagnosticsCallbacks.remove(iCb);
9293 if (cbInfo == null) {
9294 if (VDBG) log("Removing diagnostics callback that is not currently registered");
9295 return;
9296 }
9297
9298 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
9299
9300 // Caller's UID must either be the registrants (if they are unregistering) or the System's
9301 // (if the Binder died)
9302 if (uid != nri.mUid && uid != Process.SYSTEM_UID) {
9303 if (DBG) loge("Uid(" + uid + ") not registrant's (" + nri.mUid + ") or System's");
9304 return;
9305 }
9306
9307 // Decrement the reference count for this NetworkRequestInfo. The reference count is
9308 // incremented when the NetworkRequestInfo is created as part of
9309 // enforceRequestCountLimit().
9310 nri.decrementRequestCount();
9311
9312 iCb.unlinkToDeath(cbInfo, 0);
9313 }
9314
9315 private void handleNetworkTestedWithExtras(
9316 @NonNull ConnectivityReportEvent reportEvent, @NonNull PersistableBundle extras) {
9317 final NetworkAgentInfo nai = reportEvent.mNai;
9318 final NetworkCapabilities networkCapabilities =
9319 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
9320 final ConnectivityReport report =
9321 new ConnectivityReport(
9322 reportEvent.mNai.network,
9323 reportEvent.mTimestampMillis,
9324 nai.linkProperties,
9325 networkCapabilities,
9326 extras);
9327 nai.setConnectivityReport(report);
Cody Kestingf1120be2020-08-03 18:01:40 -07009328
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00009329 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -07009330 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00009331 for (final IConnectivityDiagnosticsCallback cb : results) {
9332 try {
9333 cb.onConnectivityReportAvailable(report);
9334 } catch (RemoteException ex) {
Cody Kestingf1120be2020-08-03 18:01:40 -07009335 loge("Error invoking onConnectivityReportAvailable", ex);
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00009336 }
9337 }
9338 }
9339
9340 private void handleDataStallSuspected(
9341 @NonNull NetworkAgentInfo nai, long timestampMillis, int detectionMethod,
9342 @NonNull PersistableBundle extras) {
9343 final NetworkCapabilities networkCapabilities =
9344 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
9345 final DataStallReport report =
9346 new DataStallReport(
9347 nai.network,
9348 timestampMillis,
9349 detectionMethod,
9350 nai.linkProperties,
9351 networkCapabilities,
9352 extras);
9353 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -07009354 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00009355 for (final IConnectivityDiagnosticsCallback cb : results) {
9356 try {
9357 cb.onDataStallSuspected(report);
9358 } catch (RemoteException ex) {
9359 loge("Error invoking onDataStallSuspected", ex);
9360 }
9361 }
9362 }
9363
9364 private void handleNetworkConnectivityReported(
Cody Kestingf1120be2020-08-03 18:01:40 -07009365 @NonNull ReportedNetworkConnectivityInfo reportedNetworkConnectivityInfo) {
9366 final NetworkAgentInfo nai = reportedNetworkConnectivityInfo.nai;
9367 final ConnectivityReport cachedReport = nai.getConnectivityReport();
9368
9369 // If the Network is being re-validated as a result of this call to
9370 // reportNetworkConnectivity(), notify all permissioned callbacks. Otherwise, only notify
9371 // permissioned callbacks registered by the reporter.
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00009372 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -07009373 getMatchingPermissionedCallbacks(
9374 nai,
9375 reportedNetworkConnectivityInfo.isNetworkRevalidating
9376 ? Process.INVALID_UID
9377 : reportedNetworkConnectivityInfo.reporterUid);
9378
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00009379 for (final IConnectivityDiagnosticsCallback cb : results) {
9380 try {
Cody Kestingf1120be2020-08-03 18:01:40 -07009381 cb.onNetworkConnectivityReported(
9382 nai.network, reportedNetworkConnectivityInfo.hasConnectivity);
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00009383 } catch (RemoteException ex) {
9384 loge("Error invoking onNetworkConnectivityReported", ex);
9385 }
Cody Kestingf1120be2020-08-03 18:01:40 -07009386
9387 // If the Network isn't re-validating, also provide the cached report. If there is no
9388 // cached report, the Network is still being validated and a report will be sent once
9389 // validation is complete. Note that networks which never undergo validation will still
9390 // have a cached ConnectivityReport with RESULT_SKIPPED.
9391 if (!reportedNetworkConnectivityInfo.isNetworkRevalidating && cachedReport != null) {
9392 try {
9393 cb.onConnectivityReportAvailable(cachedReport);
9394 } catch (RemoteException ex) {
9395 loge("Error invoking onConnectivityReportAvailable", ex);
9396 }
9397 }
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00009398 }
9399 }
9400
9401 private NetworkCapabilities getNetworkCapabilitiesWithoutUids(@NonNull NetworkCapabilities nc) {
9402 final NetworkCapabilities sanitized = new NetworkCapabilities(nc,
9403 NetworkCapabilities.REDACT_ALL);
9404 sanitized.setUids(null);
9405 sanitized.setAdministratorUids(new int[0]);
9406 sanitized.setOwnerUid(Process.INVALID_UID);
9407 return sanitized;
9408 }
9409
Cody Kestingf1120be2020-08-03 18:01:40 -07009410 /**
9411 * Gets a list of ConnectivityDiagnostics callbacks that match the specified Network and uid.
9412 *
9413 * <p>If Process.INVALID_UID is specified, all matching callbacks will be returned.
9414 */
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00009415 private List<IConnectivityDiagnosticsCallback> getMatchingPermissionedCallbacks(
Cody Kestingf1120be2020-08-03 18:01:40 -07009416 @NonNull NetworkAgentInfo nai, int uid) {
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00009417 final List<IConnectivityDiagnosticsCallback> results = new ArrayList<>();
9418 for (Entry<IBinder, ConnectivityDiagnosticsCallbackInfo> entry :
9419 mConnectivityDiagnosticsCallbacks.entrySet()) {
9420 final ConnectivityDiagnosticsCallbackInfo cbInfo = entry.getValue();
9421 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kestingf1120be2020-08-03 18:01:40 -07009422
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00009423 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0).
Cody Kestingf1120be2020-08-03 18:01:40 -07009424 if (!nai.satisfies(nri.mRequests.get(0))) {
9425 continue;
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00009426 }
Cody Kestingf1120be2020-08-03 18:01:40 -07009427
9428 // UID for this callback must either be:
9429 // - INVALID_UID (which sends callbacks to all UIDs), or
9430 // - The callback's owner (the owner called reportNetworkConnectivity() and is being
9431 // notified as a result)
9432 if (uid != Process.INVALID_UID && uid != nri.mUid) {
9433 continue;
9434 }
9435
9436 if (!checkConnectivityDiagnosticsPermissions(
9437 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
9438 continue;
9439 }
9440
9441 results.add(entry.getValue().mCb);
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00009442 }
9443 return results;
9444 }
9445
Cody Kesting7474f672021-05-11 14:22:40 -07009446 private boolean isLocationPermissionRequiredForConnectivityDiagnostics(
9447 @NonNull NetworkAgentInfo nai) {
9448 // TODO(b/188483916): replace with a transport-agnostic location-aware check
9449 return nai.networkCapabilities.hasTransport(TRANSPORT_WIFI);
9450 }
9451
Cody Kesting0b4be022021-05-20 22:57:07 +00009452 private boolean hasLocationPermission(String packageName, int uid) {
9453 // LocationPermissionChecker#checkLocationPermission can throw SecurityException if the uid
9454 // and package name don't match. Throwing on the CS thread is not acceptable, so wrap the
9455 // call in a try-catch.
9456 try {
9457 if (!mLocationPermissionChecker.checkLocationPermission(
9458 packageName, null /* featureId */, uid, null /* message */)) {
9459 return false;
9460 }
9461 } catch (SecurityException e) {
9462 return false;
9463 }
9464
9465 return true;
9466 }
9467
9468 private boolean ownsVpnRunningOverNetwork(int uid, Network network) {
9469 for (NetworkAgentInfo virtual : mNetworkAgentInfos) {
Lorenzo Colittibd079452021-07-02 11:47:57 +09009470 if (virtual.propagateUnderlyingCapabilities()
Cody Kesting0b4be022021-05-20 22:57:07 +00009471 && virtual.networkCapabilities.getOwnerUid() == uid
9472 && CollectionUtils.contains(virtual.declaredUnderlyingNetworks, network)) {
9473 return true;
9474 }
9475 }
9476
9477 return false;
9478 }
9479
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00009480 @VisibleForTesting
9481 boolean checkConnectivityDiagnosticsPermissions(
9482 int callbackPid, int callbackUid, NetworkAgentInfo nai, String callbackPackageName) {
9483 if (checkNetworkStackPermission(callbackPid, callbackUid)) {
9484 return true;
9485 }
9486
Cody Kesting0b4be022021-05-20 22:57:07 +00009487 // Administrator UIDs also contains the Owner UID
9488 final int[] administratorUids = nai.networkCapabilities.getAdministratorUids();
9489 if (!CollectionUtils.contains(administratorUids, callbackUid)
9490 && !ownsVpnRunningOverNetwork(callbackUid, nai.network)) {
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00009491 return false;
9492 }
9493
Cody Kesting7474f672021-05-11 14:22:40 -07009494 return !isLocationPermissionRequiredForConnectivityDiagnostics(nai)
9495 || hasLocationPermission(callbackPackageName, callbackUid);
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00009496 }
9497
9498 @Override
9499 public void registerConnectivityDiagnosticsCallback(
9500 @NonNull IConnectivityDiagnosticsCallback callback,
9501 @NonNull NetworkRequest request,
9502 @NonNull String callingPackageName) {
9503 if (request.legacyType != TYPE_NONE) {
9504 throw new IllegalArgumentException("ConnectivityManager.TYPE_* are deprecated."
9505 + " Please use NetworkCapabilities instead.");
9506 }
9507 final int callingUid = mDeps.getCallingUid();
9508 mAppOpsManager.checkPackage(callingUid, callingPackageName);
9509
9510 // This NetworkCapabilities is only used for matching to Networks. Clear out its owner uid
9511 // and administrator uids to be safe.
9512 final NetworkCapabilities nc = new NetworkCapabilities(request.networkCapabilities);
9513 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
9514
9515 final NetworkRequest requestWithId =
9516 new NetworkRequest(
9517 nc, TYPE_NONE, nextNetworkRequestId(), NetworkRequest.Type.LISTEN);
9518
9519 // NetworkRequestInfos created here count towards MAX_NETWORK_REQUESTS_PER_UID limit.
9520 //
9521 // nri is not bound to the death of callback. Instead, callback.bindToDeath() is set in
9522 // handleRegisterConnectivityDiagnosticsCallback(). nri will be cleaned up as part of the
9523 // callback's binder death.
9524 final NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, requestWithId);
9525 final ConnectivityDiagnosticsCallbackInfo cbInfo =
9526 new ConnectivityDiagnosticsCallbackInfo(callback, nri, callingPackageName);
9527
9528 mConnectivityDiagnosticsHandler.sendMessage(
9529 mConnectivityDiagnosticsHandler.obtainMessage(
9530 ConnectivityDiagnosticsHandler
9531 .EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
9532 cbInfo));
9533 }
9534
9535 @Override
9536 public void unregisterConnectivityDiagnosticsCallback(
9537 @NonNull IConnectivityDiagnosticsCallback callback) {
9538 Objects.requireNonNull(callback, "callback must be non-null");
9539 mConnectivityDiagnosticsHandler.sendMessage(
9540 mConnectivityDiagnosticsHandler.obtainMessage(
9541 ConnectivityDiagnosticsHandler
9542 .EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
9543 mDeps.getCallingUid(),
9544 0,
9545 callback));
9546 }
9547
9548 @Override
9549 public void simulateDataStall(int detectionMethod, long timestampMillis,
9550 @NonNull Network network, @NonNull PersistableBundle extras) {
9551 enforceAnyPermissionOf(android.Manifest.permission.MANAGE_TEST_NETWORKS,
9552 android.Manifest.permission.NETWORK_STACK);
9553 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
9554 if (!nc.hasTransport(TRANSPORT_TEST)) {
9555 throw new SecurityException("Data Stall simluation is only possible for test networks");
9556 }
9557
9558 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
9559 if (nai == null || nai.creatorUid != mDeps.getCallingUid()) {
9560 throw new SecurityException("Data Stall simulation is only possible for network "
9561 + "creators");
9562 }
9563
9564 // Instead of passing the data stall directly to the ConnectivityDiagnostics handler, treat
9565 // this as a Data Stall received directly from NetworkMonitor. This requires wrapping the
9566 // Data Stall information as a DataStallReportParcelable and passing to
9567 // #notifyDataStallSuspected. This ensures that unknown Data Stall detection methods are
9568 // still passed to ConnectivityDiagnostics (with new detection methods masked).
9569 final DataStallReportParcelable p = new DataStallReportParcelable();
9570 p.timestampMillis = timestampMillis;
9571 p.detectionMethod = detectionMethod;
9572
9573 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
9574 p.dnsConsecutiveTimeouts = extras.getInt(KEY_DNS_CONSECUTIVE_TIMEOUTS);
9575 }
9576 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
9577 p.tcpPacketFailRate = extras.getInt(KEY_TCP_PACKET_FAIL_RATE);
9578 p.tcpMetricsCollectionPeriodMillis = extras.getInt(
9579 KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS);
9580 }
9581
9582 notifyDataStallSuspected(p, network.getNetId());
9583 }
9584
9585 private class NetdCallback extends BaseNetdUnsolicitedEventListener {
9586 @Override
9587 public void onInterfaceClassActivityChanged(boolean isActive, int transportType,
9588 long timestampNs, int uid) {
9589 mNetworkActivityTracker.setAndReportNetworkActive(isActive, transportType, timestampNs);
9590 }
9591
9592 @Override
9593 public void onInterfaceLinkStateChanged(String iface, boolean up) {
9594 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
9595 nai.clatd.interfaceLinkStateChanged(iface, up);
9596 }
9597 }
9598
9599 @Override
9600 public void onInterfaceRemoved(String iface) {
9601 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
9602 nai.clatd.interfaceRemoved(iface);
9603 }
9604 }
9605 }
9606
9607 private final LegacyNetworkActivityTracker mNetworkActivityTracker;
9608
9609 /**
9610 * Class used for updating network activity tracking with netd and notify network activity
9611 * changes.
9612 */
9613 private static final class LegacyNetworkActivityTracker {
9614 private static final int NO_UID = -1;
9615 private final Context mContext;
9616 private final INetd mNetd;
9617 private final RemoteCallbackList<INetworkActivityListener> mNetworkActivityListeners =
9618 new RemoteCallbackList<>();
9619 // Indicate the current system default network activity is active or not.
9620 @GuardedBy("mActiveIdleTimers")
9621 private boolean mNetworkActive;
9622 @GuardedBy("mActiveIdleTimers")
9623 private final ArrayMap<String, IdleTimerParams> mActiveIdleTimers = new ArrayMap();
9624 private final Handler mHandler;
9625
9626 private class IdleTimerParams {
9627 public final int timeout;
9628 public final int transportType;
9629
9630 IdleTimerParams(int timeout, int transport) {
9631 this.timeout = timeout;
9632 this.transportType = transport;
9633 }
9634 }
9635
9636 LegacyNetworkActivityTracker(@NonNull Context context, @NonNull Handler handler,
9637 @NonNull INetd netd) {
9638 mContext = context;
9639 mNetd = netd;
9640 mHandler = handler;
9641 }
9642
9643 public void setAndReportNetworkActive(boolean active, int transportType, long tsNanos) {
9644 sendDataActivityBroadcast(transportTypeToLegacyType(transportType), active, tsNanos);
9645 synchronized (mActiveIdleTimers) {
9646 mNetworkActive = active;
9647 // If there are no idle timers, it means that system is not monitoring
9648 // activity, so the system default network for those default network
9649 // unspecified apps is always considered active.
9650 //
9651 // TODO: If the mActiveIdleTimers is empty, netd will actually not send
9652 // any network activity change event. Whenever this event is received,
9653 // the mActiveIdleTimers should be always not empty. The legacy behavior
9654 // is no-op. Remove to refer to mNetworkActive only.
9655 if (mNetworkActive || mActiveIdleTimers.isEmpty()) {
9656 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REPORT_NETWORK_ACTIVITY));
9657 }
9658 }
9659 }
9660
9661 // The network activity should only be updated from ConnectivityService handler thread
9662 // when mActiveIdleTimers lock is held.
9663 @GuardedBy("mActiveIdleTimers")
9664 private void reportNetworkActive() {
9665 final int length = mNetworkActivityListeners.beginBroadcast();
9666 if (DDBG) log("reportNetworkActive, notify " + length + " listeners");
9667 try {
9668 for (int i = 0; i < length; i++) {
9669 try {
9670 mNetworkActivityListeners.getBroadcastItem(i).onNetworkActive();
9671 } catch (RemoteException | RuntimeException e) {
9672 loge("Fail to send network activie to listener " + e);
9673 }
9674 }
9675 } finally {
9676 mNetworkActivityListeners.finishBroadcast();
9677 }
9678 }
9679
9680 @GuardedBy("mActiveIdleTimers")
9681 public void handleReportNetworkActivity() {
9682 synchronized (mActiveIdleTimers) {
9683 reportNetworkActive();
9684 }
9685 }
9686
9687 // This is deprecated and only to support legacy use cases.
9688 private int transportTypeToLegacyType(int type) {
9689 switch (type) {
9690 case NetworkCapabilities.TRANSPORT_CELLULAR:
9691 return TYPE_MOBILE;
9692 case NetworkCapabilities.TRANSPORT_WIFI:
9693 return TYPE_WIFI;
9694 case NetworkCapabilities.TRANSPORT_BLUETOOTH:
9695 return TYPE_BLUETOOTH;
9696 case NetworkCapabilities.TRANSPORT_ETHERNET:
9697 return TYPE_ETHERNET;
9698 default:
9699 loge("Unexpected transport in transportTypeToLegacyType: " + type);
9700 }
9701 return ConnectivityManager.TYPE_NONE;
9702 }
9703
9704 public void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
9705 final Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
9706 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
9707 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
9708 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
9709 final long ident = Binder.clearCallingIdentity();
9710 try {
9711 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
9712 RECEIVE_DATA_ACTIVITY_CHANGE,
9713 null /* resultReceiver */,
9714 null /* scheduler */,
9715 0 /* initialCode */,
9716 null /* initialData */,
9717 null /* initialExtra */);
9718 } finally {
9719 Binder.restoreCallingIdentity(ident);
9720 }
9721 }
9722
9723 /**
9724 * Setup data activity tracking for the given network.
9725 *
9726 * Every {@code setupDataActivityTracking} should be paired with a
9727 * {@link #removeDataActivityTracking} for cleanup.
9728 */
9729 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
9730 final String iface = networkAgent.linkProperties.getInterfaceName();
9731
9732 final int timeout;
9733 final int type;
9734
9735 if (networkAgent.networkCapabilities.hasTransport(
9736 NetworkCapabilities.TRANSPORT_CELLULAR)) {
9737 timeout = Settings.Global.getInt(mContext.getContentResolver(),
9738 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_MOBILE,
9739 10);
9740 type = NetworkCapabilities.TRANSPORT_CELLULAR;
9741 } else if (networkAgent.networkCapabilities.hasTransport(
9742 NetworkCapabilities.TRANSPORT_WIFI)) {
9743 timeout = Settings.Global.getInt(mContext.getContentResolver(),
9744 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_WIFI,
9745 15);
9746 type = NetworkCapabilities.TRANSPORT_WIFI;
9747 } else {
9748 return; // do not track any other networks
9749 }
9750
9751 updateRadioPowerState(true /* isActive */, type);
9752
9753 if (timeout > 0 && iface != null) {
9754 try {
9755 synchronized (mActiveIdleTimers) {
9756 // Networks start up.
9757 mNetworkActive = true;
9758 mActiveIdleTimers.put(iface, new IdleTimerParams(timeout, type));
9759 mNetd.idletimerAddInterface(iface, timeout, Integer.toString(type));
9760 reportNetworkActive();
9761 }
9762 } catch (Exception e) {
9763 // You shall not crash!
9764 loge("Exception in setupDataActivityTracking " + e);
9765 }
9766 }
9767 }
9768
9769 /**
9770 * Remove data activity tracking when network disconnects.
9771 */
9772 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
9773 final String iface = networkAgent.linkProperties.getInterfaceName();
9774 final NetworkCapabilities caps = networkAgent.networkCapabilities;
9775
9776 if (iface == null) return;
9777
9778 final int type;
9779 if (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
9780 type = NetworkCapabilities.TRANSPORT_CELLULAR;
9781 } else if (caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
9782 type = NetworkCapabilities.TRANSPORT_WIFI;
9783 } else {
9784 return; // do not track any other networks
9785 }
9786
9787 try {
9788 updateRadioPowerState(false /* isActive */, type);
9789 synchronized (mActiveIdleTimers) {
9790 final IdleTimerParams params = mActiveIdleTimers.remove(iface);
9791 // The call fails silently if no idle timer setup for this interface
9792 mNetd.idletimerRemoveInterface(iface, params.timeout,
9793 Integer.toString(params.transportType));
9794 }
9795 } catch (Exception e) {
9796 // You shall not crash!
9797 loge("Exception in removeDataActivityTracking " + e);
9798 }
9799 }
9800
9801 /**
9802 * Update data activity tracking when network state is updated.
9803 */
9804 public void updateDataActivityTracking(NetworkAgentInfo newNetwork,
9805 NetworkAgentInfo oldNetwork) {
9806 if (newNetwork != null) {
9807 setupDataActivityTracking(newNetwork);
9808 }
9809 if (oldNetwork != null) {
9810 removeDataActivityTracking(oldNetwork);
9811 }
9812 }
9813
9814 private void updateRadioPowerState(boolean isActive, int transportType) {
9815 final BatteryStatsManager bs = mContext.getSystemService(BatteryStatsManager.class);
9816 switch (transportType) {
9817 case NetworkCapabilities.TRANSPORT_CELLULAR:
9818 bs.reportMobileRadioPowerState(isActive, NO_UID);
9819 break;
9820 case NetworkCapabilities.TRANSPORT_WIFI:
9821 bs.reportWifiRadioPowerState(isActive, NO_UID);
9822 break;
9823 default:
9824 logw("Untracked transport type:" + transportType);
9825 }
9826 }
9827
9828 public boolean isDefaultNetworkActive() {
9829 synchronized (mActiveIdleTimers) {
9830 // If there are no idle timers, it means that system is not monitoring activity,
9831 // so the default network is always considered active.
9832 //
9833 // TODO : Distinguish between the cases where mActiveIdleTimers is empty because
9834 // tracking is disabled (negative idle timer value configured), or no active default
9835 // network. In the latter case, this reports active but it should report inactive.
9836 return mNetworkActive || mActiveIdleTimers.isEmpty();
9837 }
9838 }
9839
9840 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
9841 mNetworkActivityListeners.register(l);
9842 }
9843
9844 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
9845 mNetworkActivityListeners.unregister(l);
9846 }
9847
9848 public void dump(IndentingPrintWriter pw) {
9849 synchronized (mActiveIdleTimers) {
9850 pw.print("mNetworkActive="); pw.println(mNetworkActive);
9851 pw.println("Idle timers:");
9852 for (HashMap.Entry<String, IdleTimerParams> ent : mActiveIdleTimers.entrySet()) {
9853 pw.print(" "); pw.print(ent.getKey()); pw.println(":");
9854 final IdleTimerParams params = ent.getValue();
9855 pw.print(" timeout="); pw.print(params.timeout);
9856 pw.print(" type="); pw.println(params.transportType);
9857 }
9858 }
9859 }
9860 }
9861
9862 /**
9863 * Registers {@link QosSocketFilter} with {@link IQosCallback}.
9864 *
9865 * @param socketInfo the socket information
9866 * @param callback the callback to register
9867 */
9868 @Override
9869 public void registerQosSocketCallback(@NonNull final QosSocketInfo socketInfo,
9870 @NonNull final IQosCallback callback) {
9871 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(socketInfo.getNetwork());
9872 if (nai == null || nai.networkCapabilities == null) {
9873 try {
9874 callback.onError(QosCallbackException.EX_TYPE_FILTER_NETWORK_RELEASED);
9875 } catch (final RemoteException ex) {
9876 loge("registerQosCallbackInternal: RemoteException", ex);
9877 }
9878 return;
9879 }
9880 registerQosCallbackInternal(new QosSocketFilter(socketInfo), callback, nai);
9881 }
9882
9883 /**
9884 * Register a {@link IQosCallback} with base {@link QosFilter}.
9885 *
9886 * @param filter the filter to register
9887 * @param callback the callback to register
9888 * @param nai the agent information related to the filter's network
9889 */
9890 @VisibleForTesting
9891 public void registerQosCallbackInternal(@NonNull final QosFilter filter,
9892 @NonNull final IQosCallback callback, @NonNull final NetworkAgentInfo nai) {
9893 if (filter == null) throw new IllegalArgumentException("filter must be non-null");
9894 if (callback == null) throw new IllegalArgumentException("callback must be non-null");
9895
9896 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
9897 enforceConnectivityRestrictedNetworksPermission();
9898 }
9899 mQosCallbackTracker.registerCallback(callback, filter, nai);
9900 }
9901
9902 /**
9903 * Unregisters the given callback.
9904 *
9905 * @param callback the callback to unregister
9906 */
9907 @Override
9908 public void unregisterQosCallback(@NonNull final IQosCallback callback) {
9909 Objects.requireNonNull(callback, "callback must be non-null");
9910 mQosCallbackTracker.unregisterCallback(callback);
9911 }
9912
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00009913 /**
9914 * Request that a user profile is put by default on a network matching a given preference.
9915 *
9916 * See the documentation for the individual preferences for a description of the supported
9917 * behaviors.
9918 *
9919 * @param profile the profile concerned.
9920 * @param preference the preference for this profile, as one of the PROFILE_NETWORK_PREFERENCE_*
9921 * constants.
9922 * @param listener an optional listener to listen for completion of the operation.
9923 */
9924 @Override
9925 public void setProfileNetworkPreference(@NonNull final UserHandle profile,
9926 @ConnectivityManager.ProfileNetworkPreference final int preference,
9927 @Nullable final IOnCompleteListener listener) {
9928 Objects.requireNonNull(profile);
9929 PermissionUtils.enforceNetworkStackPermission(mContext);
9930 if (DBG) {
9931 log("setProfileNetworkPreference " + profile + " to " + preference);
9932 }
9933 if (profile.getIdentifier() < 0) {
9934 throw new IllegalArgumentException("Must explicitly specify a user handle ("
9935 + "UserHandle.CURRENT not supported)");
9936 }
9937 final UserManager um = mContext.getSystemService(UserManager.class);
9938 if (!um.isManagedProfile(profile.getIdentifier())) {
9939 throw new IllegalArgumentException("Profile must be a managed profile");
9940 }
paulhude5efb92021-05-26 21:56:03 +08009941
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00009942 final NetworkCapabilities nc;
9943 switch (preference) {
9944 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT:
9945 nc = null;
9946 break;
9947 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE:
9948 final UidRange uids = UidRange.createForUser(profile);
9949 nc = createDefaultNetworkCapabilitiesForUidRange(uids);
9950 nc.addCapability(NET_CAPABILITY_ENTERPRISE);
9951 nc.removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
9952 break;
9953 default:
9954 throw new IllegalArgumentException(
9955 "Invalid preference in setProfileNetworkPreference");
9956 }
9957 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_PROFILE_NETWORK_PREFERENCE,
9958 new Pair<>(new ProfileNetworkPreferences.Preference(profile, nc), listener)));
9959 }
9960
9961 private void validateNetworkCapabilitiesOfProfileNetworkPreference(
9962 @Nullable final NetworkCapabilities nc) {
9963 if (null == nc) return; // Null caps are always allowed. It means to remove the setting.
9964 ensureRequestableCapabilities(nc);
9965 }
9966
9967 private ArraySet<NetworkRequestInfo> createNrisFromProfileNetworkPreferences(
9968 @NonNull final ProfileNetworkPreferences prefs) {
9969 final ArraySet<NetworkRequestInfo> result = new ArraySet<>();
9970 for (final ProfileNetworkPreferences.Preference pref : prefs.preferences) {
9971 // The NRI for a user should be comprised of two layers:
9972 // - The request for the capabilities
9973 // - The request for the default network, for fallback. Create an image of it to
9974 // have the correct UIDs in it (also a request can only be part of one NRI, because
9975 // of lookups in 1:1 associations like mNetworkRequests).
9976 // Note that denying a fallback can be implemented simply by not adding the second
9977 // request.
9978 final ArrayList<NetworkRequest> nrs = new ArrayList<>();
9979 nrs.add(createNetworkRequest(NetworkRequest.Type.REQUEST, pref.capabilities));
9980 nrs.add(createDefaultInternetRequestForTransport(
9981 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
9982 setNetworkRequestUids(nrs, UidRange.fromIntRanges(pref.capabilities.getUids()));
paulhuc2198772021-05-26 15:19:20 +08009983 final NetworkRequestInfo nri = new NetworkRequestInfo(Process.myUid(), nrs,
paulhu48291862021-07-14 14:53:57 +08009984 PREFERENCE_ORDER_PROFILE);
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00009985 result.add(nri);
9986 }
9987 return result;
9988 }
9989
9990 private void handleSetProfileNetworkPreference(
9991 @NonNull final ProfileNetworkPreferences.Preference preference,
9992 @Nullable final IOnCompleteListener listener) {
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00009993 validateNetworkCapabilitiesOfProfileNetworkPreference(preference.capabilities);
9994
9995 mProfileNetworkPreferences = mProfileNetworkPreferences.plus(preference);
9996 mSystemNetworkRequestCounter.transact(
9997 mDeps.getCallingUid(), mProfileNetworkPreferences.preferences.size(),
9998 () -> {
9999 final ArraySet<NetworkRequestInfo> nris =
10000 createNrisFromProfileNetworkPreferences(mProfileNetworkPreferences);
paulhu48291862021-07-14 14:53:57 +080010001 replaceDefaultNetworkRequestsForPreference(nris, PREFERENCE_ORDER_PROFILE);
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +000010002 });
10003 // Finally, rematch.
10004 rematchAllNetworksAndRequests();
10005
10006 if (null != listener) {
10007 try {
10008 listener.onComplete();
10009 } catch (RemoteException e) {
10010 loge("Listener for setProfileNetworkPreference has died");
10011 }
10012 }
10013 }
10014
paulhu71ad4f12021-05-25 14:56:27 +080010015 @VisibleForTesting
10016 @NonNull
10017 ArraySet<NetworkRequestInfo> createNrisFromMobileDataPreferredUids(
10018 @NonNull final Set<Integer> uids) {
10019 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
10020 if (uids.size() == 0) {
10021 // Should not create NetworkRequestInfo if no preferences. Without uid range in
10022 // NetworkRequestInfo, makeDefaultForApps() would treat it as a illegal NRI.
10023 if (DBG) log("Don't create NetworkRequestInfo because no preferences");
10024 return nris;
10025 }
10026
10027 final List<NetworkRequest> requests = new ArrayList<>();
10028 // The NRI should be comprised of two layers:
10029 // - The request for the mobile network preferred.
10030 // - The request for the default network, for fallback.
10031 requests.add(createDefaultInternetRequestForTransport(
Ansik605e7702021-06-29 19:06:37 +090010032 TRANSPORT_CELLULAR, NetworkRequest.Type.REQUEST));
paulhu71ad4f12021-05-25 14:56:27 +080010033 requests.add(createDefaultInternetRequestForTransport(
10034 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
10035 final Set<UidRange> ranges = new ArraySet<>();
10036 for (final int uid : uids) {
10037 ranges.add(new UidRange(uid, uid));
10038 }
10039 setNetworkRequestUids(requests, ranges);
paulhuc2198772021-05-26 15:19:20 +080010040 nris.add(new NetworkRequestInfo(Process.myUid(), requests,
paulhu48291862021-07-14 14:53:57 +080010041 PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED));
paulhu71ad4f12021-05-25 14:56:27 +080010042 return nris;
10043 }
10044
10045 private void handleMobileDataPreferredUidsChanged() {
paulhu71ad4f12021-05-25 14:56:27 +080010046 mMobileDataPreferredUids = ConnectivitySettingsManager.getMobileDataPreferredUids(mContext);
10047 mSystemNetworkRequestCounter.transact(
10048 mDeps.getCallingUid(), 1 /* numOfNewRequests */,
10049 () -> {
10050 final ArraySet<NetworkRequestInfo> nris =
10051 createNrisFromMobileDataPreferredUids(mMobileDataPreferredUids);
paulhude5efb92021-05-26 21:56:03 +080010052 replaceDefaultNetworkRequestsForPreference(nris,
paulhu48291862021-07-14 14:53:57 +080010053 PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED);
paulhu71ad4f12021-05-25 14:56:27 +080010054 });
10055 // Finally, rematch.
10056 rematchAllNetworksAndRequests();
10057 }
10058
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +000010059 private void enforceAutomotiveDevice() {
10060 final boolean isAutomotiveDevice =
10061 mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE);
10062 if (!isAutomotiveDevice) {
10063 throw new UnsupportedOperationException(
10064 "setOemNetworkPreference() is only available on automotive devices.");
10065 }
10066 }
10067
10068 /**
10069 * Used by automotive devices to set the network preferences used to direct traffic at an
10070 * application level as per the given OemNetworkPreferences. An example use-case would be an
10071 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
10072 * vehicle via a particular network.
10073 *
10074 * Calling this will overwrite the existing preference.
10075 *
10076 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
10077 * @param listener {@link ConnectivityManager.OnCompleteListener} Listener used
10078 * to communicate completion of setOemNetworkPreference();
10079 */
10080 @Override
10081 public void setOemNetworkPreference(
10082 @NonNull final OemNetworkPreferences preference,
10083 @Nullable final IOnCompleteListener listener) {
10084
James Mattisfa270db2021-05-31 17:11:10 -070010085 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
10086 // Only bypass the permission/device checks if this is a valid test request.
10087 if (isValidTestOemNetworkPreference(preference)) {
10088 enforceManageTestNetworksPermission();
10089 } else {
10090 enforceAutomotiveDevice();
10091 enforceOemNetworkPreferencesPermission();
10092 validateOemNetworkPreferences(preference);
10093 }
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +000010094
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +000010095 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_OEM_NETWORK_PREFERENCE,
10096 new Pair<>(preference, listener)));
10097 }
10098
James Mattisfa270db2021-05-31 17:11:10 -070010099 /**
10100 * Check the validity of an OEM network preference to be used for testing purposes.
10101 * @param preference the preference to validate
10102 * @return true if this is a valid OEM network preference test request.
10103 */
10104 private boolean isValidTestOemNetworkPreference(
10105 @NonNull final OemNetworkPreferences preference) {
10106 // Allow for clearing of an existing OemNetworkPreference used for testing.
10107 // This isn't called on the handler thread so it is possible that mOemNetworkPreferences
10108 // changes after this check is complete. This is an unlikely scenario as calling of this API
10109 // is controlled by the OEM therefore the added complexity is not worth adding given those
10110 // circumstances. That said, it is an edge case to be aware of hence this comment.
10111 final boolean isValidTestClearPref = preference.getNetworkPreferences().size() == 0
10112 && isTestOemNetworkPreference(mOemNetworkPreferences);
10113 return isTestOemNetworkPreference(preference) || isValidTestClearPref;
10114 }
10115
10116 private boolean isTestOemNetworkPreference(@NonNull final OemNetworkPreferences preference) {
10117 final Map<String, Integer> prefMap = preference.getNetworkPreferences();
10118 return prefMap.size() == 1
10119 && (prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST)
10120 || prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST_ONLY));
10121 }
10122
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +000010123 private void validateOemNetworkPreferences(@NonNull OemNetworkPreferences preference) {
10124 for (@OemNetworkPreferences.OemNetworkPreference final int pref
10125 : preference.getNetworkPreferences().values()) {
James Mattisfa270db2021-05-31 17:11:10 -070010126 if (pref <= 0 || OemNetworkPreferences.OEM_NETWORK_PREFERENCE_MAX < pref) {
10127 throw new IllegalArgumentException(
10128 OemNetworkPreferences.oemNetworkPreferenceToString(pref)
10129 + " is an invalid value.");
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +000010130 }
10131 }
10132 }
10133
10134 private void handleSetOemNetworkPreference(
10135 @NonNull final OemNetworkPreferences preference,
10136 @Nullable final IOnCompleteListener listener) {
10137 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
10138 if (DBG) {
10139 log("set OEM network preferences :" + preference.toString());
10140 }
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +000010141
10142 mOemNetworkPreferencesLogs.log("UPDATE INITIATED: " + preference);
10143 final int uniquePreferenceCount = new ArraySet<>(
10144 preference.getNetworkPreferences().values()).size();
10145 mSystemNetworkRequestCounter.transact(
10146 mDeps.getCallingUid(), uniquePreferenceCount,
10147 () -> {
10148 final ArraySet<NetworkRequestInfo> nris =
10149 new OemNetworkRequestFactory()
10150 .createNrisFromOemNetworkPreferences(preference);
paulhu48291862021-07-14 14:53:57 +080010151 replaceDefaultNetworkRequestsForPreference(nris, PREFERENCE_ORDER_OEM);
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +000010152 });
10153 mOemNetworkPreferences = preference;
10154
10155 if (null != listener) {
10156 try {
10157 listener.onComplete();
10158 } catch (RemoteException e) {
10159 loge("Can't send onComplete in handleSetOemNetworkPreference", e);
10160 }
10161 }
10162 }
10163
10164 private void replaceDefaultNetworkRequestsForPreference(
paulhu48291862021-07-14 14:53:57 +080010165 @NonNull final Set<NetworkRequestInfo> nris, final int preferenceOrder) {
paulhude5efb92021-05-26 21:56:03 +080010166 // Skip the requests which are set by other network preference. Because the uid range rules
10167 // should stay in netd.
10168 final Set<NetworkRequestInfo> requests = new ArraySet<>(mDefaultNetworkRequests);
paulhu48291862021-07-14 14:53:57 +080010169 requests.removeIf(request -> request.mPreferenceOrder != preferenceOrder);
paulhude5efb92021-05-26 21:56:03 +080010170 handleRemoveNetworkRequests(requests);
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +000010171 addPerAppDefaultNetworkRequests(nris);
10172 }
10173
10174 private void addPerAppDefaultNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
10175 ensureRunningOnConnectivityServiceThread();
10176 mDefaultNetworkRequests.addAll(nris);
10177 final ArraySet<NetworkRequestInfo> perAppCallbackRequestsToUpdate =
10178 getPerAppCallbackRequestsToUpdate();
10179 final ArraySet<NetworkRequestInfo> nrisToRegister = new ArraySet<>(nris);
10180 mSystemNetworkRequestCounter.transact(
10181 mDeps.getCallingUid(), perAppCallbackRequestsToUpdate.size(),
10182 () -> {
10183 nrisToRegister.addAll(
10184 createPerAppCallbackRequestsToRegister(perAppCallbackRequestsToUpdate));
10185 handleRemoveNetworkRequests(perAppCallbackRequestsToUpdate);
10186 handleRegisterNetworkRequests(nrisToRegister);
10187 });
10188 }
10189
10190 /**
10191 * All current requests that are tracking the default network need to be assessed as to whether
10192 * or not the current set of per-application default requests will be changing their default
10193 * network. If so, those requests will need to be updated so that they will send callbacks for
10194 * default network changes at the appropriate time. Additionally, those requests tracking the
10195 * default that were previously updated by this flow will need to be reassessed.
10196 * @return the nris which will need to be updated.
10197 */
10198 private ArraySet<NetworkRequestInfo> getPerAppCallbackRequestsToUpdate() {
10199 final ArraySet<NetworkRequestInfo> defaultCallbackRequests = new ArraySet<>();
10200 // Get the distinct nris to check since for multilayer requests, it is possible to have the
10201 // same nri in the map's values for each of its NetworkRequest objects.
10202 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>(mNetworkRequests.values());
10203 for (final NetworkRequestInfo nri : nris) {
10204 // Include this nri if it is currently being tracked.
10205 if (isPerAppTrackedNri(nri)) {
10206 defaultCallbackRequests.add(nri);
10207 continue;
10208 }
10209 // We only track callbacks for requests tracking the default.
10210 if (NetworkRequest.Type.TRACK_DEFAULT != nri.mRequests.get(0).type) {
10211 continue;
10212 }
10213 // Include this nri if it will be tracked by the new per-app default requests.
10214 final boolean isNriGoingToBeTracked =
10215 getDefaultRequestTrackingUid(nri.mAsUid) != mDefaultRequest;
10216 if (isNriGoingToBeTracked) {
10217 defaultCallbackRequests.add(nri);
10218 }
10219 }
10220 return defaultCallbackRequests;
10221 }
10222
10223 /**
10224 * Create nris for those network requests that are currently tracking the default network that
10225 * are being controlled by a per-application default.
10226 * @param perAppCallbackRequestsForUpdate the baseline network requests to be used as the
10227 * foundation when creating the nri. Important items include the calling uid's original
10228 * NetworkRequest to be used when mapping callbacks as well as the caller's uid and name. These
10229 * requests are assumed to have already been validated as needing to be updated.
10230 * @return the Set of nris to use when registering network requests.
10231 */
10232 private ArraySet<NetworkRequestInfo> createPerAppCallbackRequestsToRegister(
10233 @NonNull final ArraySet<NetworkRequestInfo> perAppCallbackRequestsForUpdate) {
10234 final ArraySet<NetworkRequestInfo> callbackRequestsToRegister = new ArraySet<>();
10235 for (final NetworkRequestInfo callbackRequest : perAppCallbackRequestsForUpdate) {
10236 final NetworkRequestInfo trackingNri =
10237 getDefaultRequestTrackingUid(callbackRequest.mAsUid);
10238
10239 // If this nri is not being tracked, the change it back to an untracked nri.
10240 if (trackingNri == mDefaultRequest) {
10241 callbackRequestsToRegister.add(new NetworkRequestInfo(
10242 callbackRequest,
10243 Collections.singletonList(callbackRequest.getNetworkRequestForCallback())));
10244 continue;
10245 }
10246
10247 final NetworkRequest request = callbackRequest.mRequests.get(0);
10248 callbackRequestsToRegister.add(new NetworkRequestInfo(
10249 callbackRequest,
10250 copyNetworkRequestsForUid(
10251 trackingNri.mRequests, callbackRequest.mAsUid,
10252 callbackRequest.mUid, request.getRequestorPackageName())));
10253 }
10254 return callbackRequestsToRegister;
10255 }
10256
10257 private static void setNetworkRequestUids(@NonNull final List<NetworkRequest> requests,
10258 @NonNull final Set<UidRange> uids) {
10259 for (final NetworkRequest req : requests) {
10260 req.networkCapabilities.setUids(UidRange.toIntRanges(uids));
10261 }
10262 }
10263
10264 /**
10265 * Class used to generate {@link NetworkRequestInfo} based off of {@link OemNetworkPreferences}.
10266 */
10267 @VisibleForTesting
10268 final class OemNetworkRequestFactory {
10269 ArraySet<NetworkRequestInfo> createNrisFromOemNetworkPreferences(
10270 @NonNull final OemNetworkPreferences preference) {
10271 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
10272 final SparseArray<Set<Integer>> uids =
10273 createUidsFromOemNetworkPreferences(preference);
10274 for (int i = 0; i < uids.size(); i++) {
10275 final int key = uids.keyAt(i);
10276 final Set<Integer> value = uids.valueAt(i);
10277 final NetworkRequestInfo nri = createNriFromOemNetworkPreferences(key, value);
10278 // No need to add an nri without any requests.
10279 if (0 == nri.mRequests.size()) {
10280 continue;
10281 }
10282 nris.add(nri);
10283 }
10284
10285 return nris;
10286 }
10287
10288 private SparseArray<Set<Integer>> createUidsFromOemNetworkPreferences(
10289 @NonNull final OemNetworkPreferences preference) {
James Mattisb6b6a432021-06-01 22:30:36 -070010290 final SparseArray<Set<Integer>> prefToUids = new SparseArray<>();
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +000010291 final PackageManager pm = mContext.getPackageManager();
10292 final List<UserHandle> users =
10293 mContext.getSystemService(UserManager.class).getUserHandles(true);
10294 if (null == users || users.size() == 0) {
10295 if (VDBG || DDBG) {
10296 log("No users currently available for setting the OEM network preference.");
10297 }
James Mattisb6b6a432021-06-01 22:30:36 -070010298 return prefToUids;
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +000010299 }
10300 for (final Map.Entry<String, Integer> entry :
10301 preference.getNetworkPreferences().entrySet()) {
10302 @OemNetworkPreferences.OemNetworkPreference final int pref = entry.getValue();
James Mattisb6b6a432021-06-01 22:30:36 -070010303 // Add the rules for all users as this policy is device wide.
10304 for (final UserHandle user : users) {
10305 try {
10306 final int uid = pm.getApplicationInfoAsUser(entry.getKey(), 0, user).uid;
10307 if (!prefToUids.contains(pref)) {
10308 prefToUids.put(pref, new ArraySet<>());
10309 }
10310 prefToUids.get(pref).add(uid);
10311 } catch (PackageManager.NameNotFoundException e) {
10312 // Although this may seem like an error scenario, it is ok that uninstalled
10313 // packages are sent on a network preference as the system will watch for
10314 // package installations associated with this network preference and update
10315 // accordingly. This is done to minimize race conditions on app install.
10316 continue;
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +000010317 }
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +000010318 }
10319 }
James Mattisb6b6a432021-06-01 22:30:36 -070010320 return prefToUids;
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +000010321 }
10322
10323 private NetworkRequestInfo createNriFromOemNetworkPreferences(
10324 @OemNetworkPreferences.OemNetworkPreference final int preference,
10325 @NonNull final Set<Integer> uids) {
10326 final List<NetworkRequest> requests = new ArrayList<>();
10327 // Requests will ultimately be evaluated by order of insertion therefore it matters.
10328 switch (preference) {
10329 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID:
10330 requests.add(createUnmeteredNetworkRequest());
10331 requests.add(createOemPaidNetworkRequest());
10332 requests.add(createDefaultInternetRequestForTransport(
10333 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
10334 break;
10335 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_NO_FALLBACK:
10336 requests.add(createUnmeteredNetworkRequest());
10337 requests.add(createOemPaidNetworkRequest());
10338 break;
10339 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_ONLY:
10340 requests.add(createOemPaidNetworkRequest());
10341 break;
10342 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PRIVATE_ONLY:
10343 requests.add(createOemPrivateNetworkRequest());
10344 break;
James Mattisfa270db2021-05-31 17:11:10 -070010345 case OEM_NETWORK_PREFERENCE_TEST:
10346 requests.add(createUnmeteredNetworkRequest());
10347 requests.add(createTestNetworkRequest());
10348 requests.add(createDefaultRequest());
10349 break;
10350 case OEM_NETWORK_PREFERENCE_TEST_ONLY:
10351 requests.add(createTestNetworkRequest());
10352 break;
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +000010353 default:
10354 // This should never happen.
10355 throw new IllegalArgumentException("createNriFromOemNetworkPreferences()"
10356 + " called with invalid preference of " + preference);
10357 }
10358
James Mattisfa270db2021-05-31 17:11:10 -070010359 final ArraySet<UidRange> ranges = new ArraySet<>();
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +000010360 for (final int uid : uids) {
10361 ranges.add(new UidRange(uid, uid));
10362 }
10363 setNetworkRequestUids(requests, ranges);
paulhu48291862021-07-14 14:53:57 +080010364 return new NetworkRequestInfo(Process.myUid(), requests, PREFERENCE_ORDER_OEM);
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +000010365 }
10366
10367 private NetworkRequest createUnmeteredNetworkRequest() {
10368 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
10369 .addCapability(NET_CAPABILITY_NOT_METERED)
10370 .addCapability(NET_CAPABILITY_VALIDATED);
10371 return createNetworkRequest(NetworkRequest.Type.LISTEN, netcap);
10372 }
10373
10374 private NetworkRequest createOemPaidNetworkRequest() {
10375 // NET_CAPABILITY_OEM_PAID is a restricted capability.
10376 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
10377 .addCapability(NET_CAPABILITY_OEM_PAID)
10378 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
10379 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
10380 }
10381
10382 private NetworkRequest createOemPrivateNetworkRequest() {
10383 // NET_CAPABILITY_OEM_PRIVATE is a restricted capability.
10384 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
10385 .addCapability(NET_CAPABILITY_OEM_PRIVATE)
10386 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
10387 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
10388 }
10389
10390 private NetworkCapabilities createDefaultPerAppNetCap() {
James Mattisfa270db2021-05-31 17:11:10 -070010391 final NetworkCapabilities netcap = new NetworkCapabilities();
10392 netcap.addCapability(NET_CAPABILITY_INTERNET);
10393 netcap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
10394 return netcap;
10395 }
10396
10397 private NetworkRequest createTestNetworkRequest() {
10398 final NetworkCapabilities netcap = new NetworkCapabilities();
10399 netcap.clearAll();
10400 netcap.addTransportType(TRANSPORT_TEST);
10401 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +000010402 }
10403 }
10404}