blob: cd6a71a47fb36378c6f4cee37efbe2cba965ad64 [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.networkstack.ModuleNetworkStackClient;
184import android.net.networkstack.NetworkStackClientBase;
185import android.net.resolv.aidl.DnsHealthEventParcel;
186import android.net.resolv.aidl.IDnsResolverUnsolicitedEventListener;
187import android.net.resolv.aidl.Nat64PrefixEventParcel;
188import android.net.resolv.aidl.PrivateDnsValidationEventParcel;
189import android.net.shared.PrivateDnsConfig;
190import android.net.util.MultinetworkPolicyTracker;
191import android.os.BatteryStatsManager;
192import android.os.Binder;
193import android.os.Build;
194import android.os.Bundle;
195import android.os.Handler;
196import android.os.HandlerThread;
197import android.os.IBinder;
198import android.os.Looper;
199import android.os.Message;
200import android.os.Messenger;
201import android.os.ParcelFileDescriptor;
202import android.os.Parcelable;
203import android.os.PersistableBundle;
204import android.os.PowerManager;
205import android.os.Process;
206import android.os.RemoteCallbackList;
207import android.os.RemoteException;
208import android.os.ServiceSpecificException;
209import android.os.SystemClock;
210import android.os.SystemProperties;
211import android.os.UserHandle;
212import android.os.UserManager;
213import android.provider.Settings;
214import android.sysprop.NetworkProperties;
215import android.telephony.TelephonyManager;
216import android.text.TextUtils;
217import android.util.ArrayMap;
218import android.util.ArraySet;
219import android.util.LocalLog;
220import android.util.Log;
221import android.util.Pair;
222import android.util.SparseArray;
223import android.util.SparseIntArray;
224
225import com.android.connectivity.resources.R;
226import com.android.internal.annotations.GuardedBy;
227import com.android.internal.annotations.VisibleForTesting;
228import com.android.internal.util.IndentingPrintWriter;
229import com.android.internal.util.MessageUtils;
230import com.android.modules.utils.BasicShellCommandHandler;
231import com.android.net.module.util.BaseNetdUnsolicitedEventListener;
232import com.android.net.module.util.CollectionUtils;
233import com.android.net.module.util.LinkPropertiesUtils.CompareOrUpdateResult;
234import com.android.net.module.util.LinkPropertiesUtils.CompareResult;
235import com.android.net.module.util.LocationPermissionChecker;
236import com.android.net.module.util.NetworkCapabilitiesUtils;
237import com.android.net.module.util.PermissionUtils;
Xiao Ma09c07272021-07-01 14:00:34 +0000238import com.android.net.module.util.netlink.InetDiagMessage;
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +0000239import 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) {
Chiachang Wangeb256742021-07-27 14:00:17 +08003173 NetworkRequestInfo[] infos = null;
3174 while (infos == null) {
3175 try {
3176 infos = requestsSortedById();
3177 } catch (ConcurrentModificationException e) {
3178 // mNetworkRequests should only be accessed from handler thread, except dump().
3179 // As dump() is never called in normal usage, it would be needlessly expensive
3180 // to lock the collection only for its benefit. Instead, retry getting the
3181 // requests if ConcurrentModificationException is thrown during dump().
3182 }
3183 }
3184 for (NetworkRequestInfo nri : infos) {
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00003185 pw.println(nri.toString());
3186 }
3187 }
3188
3189 /**
3190 * Return an array of all current NetworkAgentInfos sorted by network id.
3191 */
3192 private NetworkAgentInfo[] networksSortedById() {
3193 NetworkAgentInfo[] networks = new NetworkAgentInfo[0];
3194 networks = mNetworkAgentInfos.toArray(networks);
3195 Arrays.sort(networks, Comparator.comparingInt(nai -> nai.network.getNetId()));
3196 return networks;
3197 }
3198
3199 /**
3200 * Return an array of all current NetworkRequest sorted by request id.
3201 */
3202 @VisibleForTesting
3203 NetworkRequestInfo[] requestsSortedById() {
3204 NetworkRequestInfo[] requests = new NetworkRequestInfo[0];
3205 requests = getNrisFromGlobalRequests().toArray(requests);
3206 // Sort the array based off the NRI containing the min requestId in its requests.
3207 Arrays.sort(requests,
3208 Comparator.comparingInt(nri -> Collections.min(nri.mRequests,
3209 Comparator.comparingInt(req -> req.requestId)).requestId
3210 )
3211 );
3212 return requests;
3213 }
3214
3215 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
3216 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
3217 if (officialNai != null && officialNai.equals(nai)) return true;
3218 if (officialNai != null || VDBG) {
3219 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
3220 " - " + nai);
3221 }
3222 return false;
3223 }
3224
3225 // must be stateless - things change under us.
3226 private class NetworkStateTrackerHandler extends Handler {
3227 public NetworkStateTrackerHandler(Looper looper) {
3228 super(looper);
3229 }
3230
3231 private void maybeHandleNetworkAgentMessage(Message msg) {
3232 final Pair<NetworkAgentInfo, Object> arg = (Pair<NetworkAgentInfo, Object>) msg.obj;
3233 final NetworkAgentInfo nai = arg.first;
3234 if (!mNetworkAgentInfos.contains(nai)) {
3235 if (VDBG) {
3236 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
3237 }
3238 return;
3239 }
3240
3241 switch (msg.what) {
3242 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
3243 NetworkCapabilities networkCapabilities = (NetworkCapabilities) arg.second;
3244 if (networkCapabilities.hasConnectivityManagedCapability()) {
3245 Log.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
3246 }
3247 if (networkCapabilities.hasTransport(TRANSPORT_TEST)) {
3248 // Make sure the original object is not mutated. NetworkAgent normally
3249 // makes a copy of the capabilities when sending the message through
3250 // the Messenger, but if this ever changes, not making a defensive copy
3251 // here will give attack vectors to clients using this code path.
3252 networkCapabilities = new NetworkCapabilities(networkCapabilities);
3253 networkCapabilities.restrictCapabilitesForTestNetwork(nai.creatorUid);
3254 }
3255 processCapabilitiesFromAgent(nai, networkCapabilities);
3256 updateCapabilities(nai.getCurrentScore(), nai, networkCapabilities);
3257 break;
3258 }
3259 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
3260 LinkProperties newLp = (LinkProperties) arg.second;
3261 processLinkPropertiesFromAgent(nai, newLp);
3262 handleUpdateLinkProperties(nai, newLp);
3263 break;
3264 }
3265 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
3266 NetworkInfo info = (NetworkInfo) arg.second;
3267 updateNetworkInfo(nai, info);
3268 break;
3269 }
3270 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
3271 updateNetworkScore(nai, (NetworkScore) arg.second);
3272 break;
3273 }
3274 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
3275 if (nai.everConnected) {
3276 loge("ERROR: cannot call explicitlySelected on already-connected network");
3277 // Note that if the NAI had been connected, this would affect the
3278 // score, and therefore would require re-mixing the score and performing
3279 // a rematch.
3280 }
3281 nai.networkAgentConfig.explicitlySelected = toBool(msg.arg1);
3282 nai.networkAgentConfig.acceptUnvalidated = toBool(msg.arg1) && toBool(msg.arg2);
3283 // Mark the network as temporarily accepting partial connectivity so that it
3284 // will be validated (and possibly become default) even if it only provides
3285 // partial internet access. Note that if user connects to partial connectivity
3286 // and choose "don't ask again", then wifi disconnected by some reasons(maybe
3287 // out of wifi coverage) and if the same wifi is available again, the device
3288 // will auto connect to this wifi even though the wifi has "no internet".
3289 // TODO: Evaluate using a separate setting in IpMemoryStore.
3290 nai.networkAgentConfig.acceptPartialConnectivity = toBool(msg.arg2);
3291 break;
3292 }
3293 case NetworkAgent.EVENT_SOCKET_KEEPALIVE: {
3294 mKeepaliveTracker.handleEventSocketKeepalive(nai, msg.arg1, msg.arg2);
3295 break;
3296 }
3297 case NetworkAgent.EVENT_UNDERLYING_NETWORKS_CHANGED: {
3298 // TODO: prevent loops, e.g., if a network declares itself as underlying.
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00003299 final List<Network> underlying = (List<Network>) arg.second;
3300
3301 if (isLegacyLockdownNai(nai)
3302 && (underlying == null || underlying.size() != 1)) {
3303 Log.wtf(TAG, "Legacy lockdown VPN " + nai.toShortString()
3304 + " must have exactly one underlying network: " + underlying);
3305 }
3306
3307 final Network[] oldUnderlying = nai.declaredUnderlyingNetworks;
3308 nai.declaredUnderlyingNetworks = (underlying != null)
3309 ? underlying.toArray(new Network[0]) : null;
3310
3311 if (!Arrays.equals(oldUnderlying, nai.declaredUnderlyingNetworks)) {
3312 if (DBG) {
3313 log(nai.toShortString() + " changed underlying networks to "
3314 + Arrays.toString(nai.declaredUnderlyingNetworks));
3315 }
3316 updateCapabilitiesForNetwork(nai);
3317 notifyIfacesChangedForNetworkStats();
3318 }
3319 break;
3320 }
3321 case NetworkAgent.EVENT_TEARDOWN_DELAY_CHANGED: {
3322 if (msg.arg1 >= 0 && msg.arg1 <= NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
3323 nai.teardownDelayMs = msg.arg1;
3324 } else {
3325 logwtf(nai.toShortString() + " set invalid teardown delay " + msg.arg1);
3326 }
3327 break;
3328 }
3329 case NetworkAgent.EVENT_LINGER_DURATION_CHANGED: {
3330 nai.setLingerDuration((int) arg.second);
3331 break;
3332 }
3333 }
3334 }
3335
3336 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
3337 switch (msg.what) {
3338 default:
3339 return false;
3340 case EVENT_PROBE_STATUS_CHANGED: {
3341 final Integer netId = (Integer) msg.obj;
3342 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
3343 if (nai == null) {
3344 break;
3345 }
3346 final boolean probePrivateDnsCompleted =
3347 ((msg.arg1 & NETWORK_VALIDATION_PROBE_PRIVDNS) != 0);
3348 final boolean privateDnsBroken =
3349 ((msg.arg2 & NETWORK_VALIDATION_PROBE_PRIVDNS) == 0);
3350 if (probePrivateDnsCompleted) {
3351 if (nai.networkCapabilities.isPrivateDnsBroken() != privateDnsBroken) {
3352 nai.networkCapabilities.setPrivateDnsBroken(privateDnsBroken);
3353 updateCapabilitiesForNetwork(nai);
3354 }
3355 // Only show the notification when the private DNS is broken and the
3356 // PRIVATE_DNS_BROKEN notification hasn't shown since last valid.
3357 if (privateDnsBroken && !nai.networkAgentConfig.hasShownBroken) {
3358 showNetworkNotification(nai, NotificationType.PRIVATE_DNS_BROKEN);
3359 }
3360 nai.networkAgentConfig.hasShownBroken = privateDnsBroken;
3361 } else if (nai.networkCapabilities.isPrivateDnsBroken()) {
3362 // If probePrivateDnsCompleted is false but nai.networkCapabilities says
3363 // private DNS is broken, it means this network is being reevaluated.
3364 // Either probing private DNS is not necessary any more or it hasn't been
3365 // done yet. In either case, the networkCapabilities should be updated to
3366 // reflect the new status.
3367 nai.networkCapabilities.setPrivateDnsBroken(false);
3368 updateCapabilitiesForNetwork(nai);
3369 nai.networkAgentConfig.hasShownBroken = false;
3370 }
3371 break;
3372 }
3373 case EVENT_NETWORK_TESTED: {
3374 final NetworkTestedResults results = (NetworkTestedResults) msg.obj;
3375
3376 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(results.mNetId);
3377 if (nai == null) break;
3378
3379 handleNetworkTested(nai, results.mTestResult,
3380 (results.mRedirectUrl == null) ? "" : results.mRedirectUrl);
3381 break;
3382 }
3383 case EVENT_PROVISIONING_NOTIFICATION: {
3384 final int netId = msg.arg2;
3385 final boolean visible = toBool(msg.arg1);
3386 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
3387 // If captive portal status has changed, update capabilities or disconnect.
3388 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
3389 nai.lastCaptivePortalDetected = visible;
3390 nai.everCaptivePortalDetected |= visible;
3391 if (nai.lastCaptivePortalDetected &&
3392 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_AVOID
3393 == getCaptivePortalMode()) {
3394 if (DBG) log("Avoiding captive portal network: " + nai.toShortString());
3395 nai.onPreventAutomaticReconnect();
3396 teardownUnneededNetwork(nai);
3397 break;
3398 }
3399 updateCapabilitiesForNetwork(nai);
3400 }
3401 if (!visible) {
3402 // Only clear SIGN_IN and NETWORK_SWITCH notifications here, or else other
3403 // notifications belong to the same network may be cleared unexpectedly.
3404 mNotifier.clearNotification(netId, NotificationType.SIGN_IN);
3405 mNotifier.clearNotification(netId, NotificationType.NETWORK_SWITCH);
3406 } else {
3407 if (nai == null) {
3408 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
3409 break;
3410 }
3411 if (!nai.networkAgentConfig.provisioningNotificationDisabled) {
3412 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
3413 (PendingIntent) msg.obj,
3414 nai.networkAgentConfig.explicitlySelected);
3415 }
3416 }
3417 break;
3418 }
3419 case EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
3420 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
3421 if (nai == null) break;
3422
3423 updatePrivateDns(nai, (PrivateDnsConfig) msg.obj);
3424 break;
3425 }
3426 case EVENT_CAPPORT_DATA_CHANGED: {
3427 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
3428 if (nai == null) break;
3429 handleCapportApiDataUpdate(nai, (CaptivePortalData) msg.obj);
3430 break;
3431 }
3432 }
3433 return true;
3434 }
3435
3436 private void handleNetworkTested(
3437 @NonNull NetworkAgentInfo nai, int testResult, @NonNull String redirectUrl) {
3438 final boolean wasPartial = nai.partialConnectivity;
3439 nai.partialConnectivity = ((testResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0);
3440 final boolean partialConnectivityChanged =
3441 (wasPartial != nai.partialConnectivity);
3442
3443 final boolean valid = ((testResult & NETWORK_VALIDATION_RESULT_VALID) != 0);
3444 final boolean wasValidated = nai.lastValidated;
3445 final boolean wasDefault = isDefaultNetwork(nai);
3446
3447 if (DBG) {
3448 final String logMsg = !TextUtils.isEmpty(redirectUrl)
3449 ? " with redirect to " + redirectUrl
3450 : "";
3451 log(nai.toShortString() + " validation " + (valid ? "passed" : "failed") + logMsg);
3452 }
3453 if (valid != nai.lastValidated) {
3454 final int oldScore = nai.getCurrentScore();
3455 nai.lastValidated = valid;
3456 nai.everValidated |= valid;
3457 updateCapabilities(oldScore, nai, nai.networkCapabilities);
3458 if (valid) {
3459 handleFreshlyValidatedNetwork(nai);
3460 // Clear NO_INTERNET, PRIVATE_DNS_BROKEN, PARTIAL_CONNECTIVITY and
3461 // LOST_INTERNET notifications if network becomes valid.
3462 mNotifier.clearNotification(nai.network.getNetId(),
3463 NotificationType.NO_INTERNET);
3464 mNotifier.clearNotification(nai.network.getNetId(),
3465 NotificationType.LOST_INTERNET);
3466 mNotifier.clearNotification(nai.network.getNetId(),
3467 NotificationType.PARTIAL_CONNECTIVITY);
3468 mNotifier.clearNotification(nai.network.getNetId(),
3469 NotificationType.PRIVATE_DNS_BROKEN);
3470 // If network becomes valid, the hasShownBroken should be reset for
3471 // that network so that the notification will be fired when the private
3472 // DNS is broken again.
3473 nai.networkAgentConfig.hasShownBroken = false;
3474 }
3475 } else if (partialConnectivityChanged) {
3476 updateCapabilitiesForNetwork(nai);
3477 }
3478 updateInetCondition(nai);
3479 // Let the NetworkAgent know the state of its network
3480 // TODO: Evaluate to update partial connectivity to status to NetworkAgent.
3481 nai.onValidationStatusChanged(
3482 valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK,
3483 redirectUrl);
3484
3485 // If NetworkMonitor detects partial connectivity before
3486 // EVENT_PROMPT_UNVALIDATED arrives, show the partial connectivity notification
3487 // immediately. Re-notify partial connectivity silently if no internet
3488 // notification already there.
3489 if (!wasPartial && nai.partialConnectivity) {
3490 // Remove delayed message if there is a pending message.
3491 mHandler.removeMessages(EVENT_PROMPT_UNVALIDATED, nai.network);
3492 handlePromptUnvalidated(nai.network);
3493 }
3494
3495 if (wasValidated && !nai.lastValidated) {
3496 handleNetworkUnvalidated(nai);
3497 }
3498 }
3499
3500 private int getCaptivePortalMode() {
3501 return Settings.Global.getInt(mContext.getContentResolver(),
3502 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE,
3503 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_PROMPT);
3504 }
3505
3506 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
3507 switch (msg.what) {
3508 default:
3509 return false;
3510 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
3511 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
3512 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
3513 handleLingerComplete(nai);
3514 }
3515 break;
3516 }
3517 case NetworkAgentInfo.EVENT_AGENT_REGISTERED: {
3518 handleNetworkAgentRegistered(msg);
3519 break;
3520 }
3521 case NetworkAgentInfo.EVENT_AGENT_DISCONNECTED: {
3522 handleNetworkAgentDisconnected(msg);
3523 break;
3524 }
3525 }
3526 return true;
3527 }
3528
3529 @Override
3530 public void handleMessage(Message msg) {
3531 if (!maybeHandleNetworkMonitorMessage(msg)
3532 && !maybeHandleNetworkAgentInfoMessage(msg)) {
3533 maybeHandleNetworkAgentMessage(msg);
3534 }
3535 }
3536 }
3537
3538 private class NetworkMonitorCallbacks extends INetworkMonitorCallbacks.Stub {
3539 private final int mNetId;
3540 private final AutodestructReference<NetworkAgentInfo> mNai;
3541
3542 private NetworkMonitorCallbacks(NetworkAgentInfo nai) {
3543 mNetId = nai.network.getNetId();
3544 mNai = new AutodestructReference<>(nai);
3545 }
3546
3547 @Override
3548 public void onNetworkMonitorCreated(INetworkMonitor networkMonitor) {
3549 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT,
3550 new Pair<>(mNai.getAndDestroy(), networkMonitor)));
3551 }
3552
3553 @Override
3554 public void notifyNetworkTested(int testResult, @Nullable String redirectUrl) {
3555 // Legacy version of notifyNetworkTestedWithExtras.
3556 // Would only be called if the system has a NetworkStack module older than the
3557 // framework, which does not happen in practice.
3558 Log.wtf(TAG, "Deprecated notifyNetworkTested called: no action taken");
3559 }
3560
3561 @Override
3562 public void notifyNetworkTestedWithExtras(NetworkTestResultParcelable p) {
3563 // Notify mTrackerHandler and mConnectivityDiagnosticsHandler of the event. Both use
3564 // the same looper so messages will be processed in sequence.
3565 final Message msg = mTrackerHandler.obtainMessage(
3566 EVENT_NETWORK_TESTED,
3567 new NetworkTestedResults(
3568 mNetId, p.result, p.timestampMillis, p.redirectUrl));
3569 mTrackerHandler.sendMessage(msg);
3570
3571 // Invoke ConnectivityReport generation for this Network test event.
3572 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(mNetId);
3573 if (nai == null) return;
3574
Cody Kestingf1120be2020-08-03 18:01:40 -07003575 // NetworkMonitor reports the network validation result as a bitmask while
3576 // ConnectivityDiagnostics treats this value as an int. Convert the result to a single
3577 // logical value for ConnectivityDiagnostics.
3578 final int validationResult = networkMonitorValidationResultToConnDiagsValidationResult(
3579 p.result);
3580
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00003581 final PersistableBundle extras = new PersistableBundle();
Cody Kestingf1120be2020-08-03 18:01:40 -07003582 extras.putInt(KEY_NETWORK_VALIDATION_RESULT, validationResult);
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00003583 extras.putInt(KEY_NETWORK_PROBES_SUCCEEDED_BITMASK, p.probesSucceeded);
3584 extras.putInt(KEY_NETWORK_PROBES_ATTEMPTED_BITMASK, p.probesAttempted);
3585
3586 ConnectivityReportEvent reportEvent =
3587 new ConnectivityReportEvent(p.timestampMillis, nai, extras);
3588 final Message m = mConnectivityDiagnosticsHandler.obtainMessage(
3589 ConnectivityDiagnosticsHandler.EVENT_NETWORK_TESTED, reportEvent);
3590 mConnectivityDiagnosticsHandler.sendMessage(m);
3591 }
3592
3593 @Override
3594 public void notifyPrivateDnsConfigResolved(PrivateDnsConfigParcel config) {
3595 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3596 EVENT_PRIVATE_DNS_CONFIG_RESOLVED,
3597 0, mNetId, PrivateDnsConfig.fromParcel(config)));
3598 }
3599
3600 @Override
3601 public void notifyProbeStatusChanged(int probesCompleted, int probesSucceeded) {
3602 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3603 EVENT_PROBE_STATUS_CHANGED,
3604 probesCompleted, probesSucceeded, new Integer(mNetId)));
3605 }
3606
3607 @Override
3608 public void notifyCaptivePortalDataChanged(CaptivePortalData data) {
3609 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3610 EVENT_CAPPORT_DATA_CHANGED,
3611 0, mNetId, data));
3612 }
3613
3614 @Override
3615 public void showProvisioningNotification(String action, String packageName) {
3616 final Intent intent = new Intent(action);
3617 intent.setPackage(packageName);
3618
3619 final PendingIntent pendingIntent;
3620 // Only the system server can register notifications with package "android"
3621 final long token = Binder.clearCallingIdentity();
3622 try {
3623 pendingIntent = PendingIntent.getBroadcast(
3624 mContext,
3625 0 /* requestCode */,
3626 intent,
3627 PendingIntent.FLAG_IMMUTABLE);
3628 } finally {
3629 Binder.restoreCallingIdentity(token);
3630 }
3631 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3632 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_SHOW,
3633 mNetId, pendingIntent));
3634 }
3635
3636 @Override
3637 public void hideProvisioningNotification() {
3638 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3639 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_HIDE, mNetId));
3640 }
3641
3642 @Override
3643 public void notifyDataStallSuspected(DataStallReportParcelable p) {
3644 ConnectivityService.this.notifyDataStallSuspected(p, mNetId);
3645 }
3646
3647 @Override
3648 public int getInterfaceVersion() {
3649 return this.VERSION;
3650 }
3651
3652 @Override
3653 public String getInterfaceHash() {
3654 return this.HASH;
3655 }
3656 }
3657
Cody Kestingf1120be2020-08-03 18:01:40 -07003658 /**
3659 * Converts the given NetworkMonitor-specific validation result bitmask to a
3660 * ConnectivityDiagnostics-specific validation result int.
3661 */
3662 private int networkMonitorValidationResultToConnDiagsValidationResult(int validationResult) {
3663 if ((validationResult & NETWORK_VALIDATION_RESULT_SKIPPED) != 0) {
3664 return ConnectivityReport.NETWORK_VALIDATION_RESULT_SKIPPED;
3665 }
3666 if ((validationResult & NETWORK_VALIDATION_RESULT_VALID) == 0) {
3667 return ConnectivityReport.NETWORK_VALIDATION_RESULT_INVALID;
3668 }
3669 return (validationResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0
3670 ? ConnectivityReport.NETWORK_VALIDATION_RESULT_PARTIALLY_VALID
3671 : ConnectivityReport.NETWORK_VALIDATION_RESULT_VALID;
3672 }
3673
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00003674 private void notifyDataStallSuspected(DataStallReportParcelable p, int netId) {
3675 log("Data stall detected with methods: " + p.detectionMethod);
3676
3677 final PersistableBundle extras = new PersistableBundle();
3678 int detectionMethod = 0;
3679 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
3680 extras.putInt(KEY_DNS_CONSECUTIVE_TIMEOUTS, p.dnsConsecutiveTimeouts);
3681 detectionMethod |= DETECTION_METHOD_DNS_EVENTS;
3682 }
3683 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
3684 extras.putInt(KEY_TCP_PACKET_FAIL_RATE, p.tcpPacketFailRate);
3685 extras.putInt(KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS,
3686 p.tcpMetricsCollectionPeriodMillis);
3687 detectionMethod |= DETECTION_METHOD_TCP_METRICS;
3688 }
3689
3690 final Message msg = mConnectivityDiagnosticsHandler.obtainMessage(
3691 ConnectivityDiagnosticsHandler.EVENT_DATA_STALL_SUSPECTED, detectionMethod, netId,
3692 new Pair<>(p.timestampMillis, extras));
3693
3694 // NetworkStateTrackerHandler currently doesn't take any actions based on data
3695 // stalls so send the message directly to ConnectivityDiagnosticsHandler and avoid
3696 // the cost of going through two handlers.
3697 mConnectivityDiagnosticsHandler.sendMessage(msg);
3698 }
3699
3700 private boolean hasDataStallDetectionMethod(DataStallReportParcelable p, int detectionMethod) {
3701 return (p.detectionMethod & detectionMethod) != 0;
3702 }
3703
3704 private boolean networkRequiresPrivateDnsValidation(NetworkAgentInfo nai) {
3705 return isPrivateDnsValidationRequired(nai.networkCapabilities);
3706 }
3707
3708 private void handleFreshlyValidatedNetwork(NetworkAgentInfo nai) {
3709 if (nai == null) return;
3710 // If the Private DNS mode is opportunistic, reprogram the DNS servers
3711 // in order to restart a validation pass from within netd.
3712 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
3713 if (cfg.useTls && TextUtils.isEmpty(cfg.hostname)) {
3714 updateDnses(nai.linkProperties, null, nai.network.getNetId());
3715 }
3716 }
3717
3718 private void handlePrivateDnsSettingsChanged() {
3719 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
3720
3721 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
3722 handlePerNetworkPrivateDnsConfig(nai, cfg);
3723 if (networkRequiresPrivateDnsValidation(nai)) {
3724 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
3725 }
3726 }
3727 }
3728
3729 private void handlePerNetworkPrivateDnsConfig(NetworkAgentInfo nai, PrivateDnsConfig cfg) {
3730 // Private DNS only ever applies to networks that might provide
3731 // Internet access and therefore also require validation.
3732 if (!networkRequiresPrivateDnsValidation(nai)) return;
3733
3734 // Notify the NetworkAgentInfo/NetworkMonitor in case NetworkMonitor needs to cancel or
3735 // schedule DNS resolutions. If a DNS resolution is required the
3736 // result will be sent back to us.
3737 nai.networkMonitor().notifyPrivateDnsChanged(cfg.toParcel());
3738
3739 // With Private DNS bypass support, we can proceed to update the
3740 // Private DNS config immediately, even if we're in strict mode
3741 // and have not yet resolved the provider name into a set of IPs.
3742 updatePrivateDns(nai, cfg);
3743 }
3744
3745 private void updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
3746 mDnsManager.updatePrivateDns(nai.network, newCfg);
3747 updateDnses(nai.linkProperties, null, nai.network.getNetId());
3748 }
3749
3750 private void handlePrivateDnsValidationUpdate(PrivateDnsValidationUpdate update) {
3751 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(update.netId);
3752 if (nai == null) {
3753 return;
3754 }
3755 mDnsManager.updatePrivateDnsValidation(update);
3756 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
3757 }
3758
3759 private void handleNat64PrefixEvent(int netId, int operation, String prefixAddress,
3760 int prefixLength) {
3761 NetworkAgentInfo nai = mNetworkForNetId.get(netId);
3762 if (nai == null) return;
3763
3764 log(String.format("NAT64 prefix changed on netId %d: operation=%d, %s/%d",
3765 netId, operation, prefixAddress, prefixLength));
3766
3767 IpPrefix prefix = null;
3768 if (operation == IDnsResolverUnsolicitedEventListener.PREFIX_OPERATION_ADDED) {
3769 try {
3770 prefix = new IpPrefix(InetAddresses.parseNumericAddress(prefixAddress),
3771 prefixLength);
3772 } catch (IllegalArgumentException e) {
3773 loge("Invalid NAT64 prefix " + prefixAddress + "/" + prefixLength);
3774 return;
3775 }
3776 }
3777
3778 nai.clatd.setNat64PrefixFromDns(prefix);
3779 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
3780 }
3781
3782 private void handleCapportApiDataUpdate(@NonNull final NetworkAgentInfo nai,
3783 @Nullable final CaptivePortalData data) {
3784 nai.capportApiData = data;
3785 // CaptivePortalData will be merged into LinkProperties from NetworkAgentInfo
3786 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
3787 }
3788
3789 /**
3790 * Updates the inactivity state from the network requests inside the NAI.
3791 * @param nai the agent info to update
3792 * @param now the timestamp of the event causing this update
3793 * @return whether the network was inactive as a result of this update
3794 */
3795 private boolean updateInactivityState(@NonNull final NetworkAgentInfo nai, final long now) {
3796 // 1. Update the inactivity timer. If it's changed, reschedule or cancel the alarm.
3797 // 2. If the network was inactive and there are now requests, unset inactive.
3798 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
3799 // one lingered request, set inactive.
3800 nai.updateInactivityTimer();
3801 if (nai.isInactive() && nai.numForegroundNetworkRequests() > 0) {
3802 if (DBG) log("Unsetting inactive " + nai.toShortString());
3803 nai.unsetInactive();
3804 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
3805 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getInactivityExpiry() > 0) {
3806 if (DBG) {
3807 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
3808 log("Setting inactive " + nai.toShortString() + " for " + lingerTime + "ms");
3809 }
3810 nai.setInactive();
3811 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
3812 return true;
3813 }
3814 return false;
3815 }
3816
3817 private void handleNetworkAgentRegistered(Message msg) {
3818 final NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
3819 if (!mNetworkAgentInfos.contains(nai)) {
3820 return;
3821 }
3822
3823 if (msg.arg1 == NetworkAgentInfo.ARG_AGENT_SUCCESS) {
3824 if (VDBG) log("NetworkAgent registered");
3825 } else {
3826 loge("Error connecting NetworkAgent");
3827 mNetworkAgentInfos.remove(nai);
3828 if (nai != null) {
3829 final boolean wasDefault = isDefaultNetwork(nai);
3830 synchronized (mNetworkForNetId) {
3831 mNetworkForNetId.remove(nai.network.getNetId());
3832 }
3833 mNetIdManager.releaseNetId(nai.network.getNetId());
3834 // Just in case.
3835 mLegacyTypeTracker.remove(nai, wasDefault);
3836 }
3837 }
3838 }
3839
3840 private void handleNetworkAgentDisconnected(Message msg) {
3841 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
3842 if (mNetworkAgentInfos.contains(nai)) {
3843 disconnectAndDestroyNetwork(nai);
3844 }
3845 }
3846
3847 // Destroys a network, remove references to it from the internal state managed by
3848 // ConnectivityService, free its interfaces and clean up.
3849 // Must be called on the Handler thread.
3850 private void disconnectAndDestroyNetwork(NetworkAgentInfo nai) {
3851 ensureRunningOnConnectivityServiceThread();
3852 if (DBG) {
3853 log(nai.toShortString() + " disconnected, was satisfying " + nai.numNetworkRequests());
3854 }
3855 // Clear all notifications of this network.
3856 mNotifier.clearNotification(nai.network.getNetId());
3857 // A network agent has disconnected.
3858 // TODO - if we move the logic to the network agent (have them disconnect
3859 // because they lost all their requests or because their score isn't good)
3860 // then they would disconnect organically, report their new state and then
3861 // disconnect the channel.
3862 if (nai.networkInfo.isConnected()) {
3863 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
3864 null, null);
3865 }
3866 final boolean wasDefault = isDefaultNetwork(nai);
3867 if (wasDefault) {
3868 mDefaultInetConditionPublished = 0;
3869 }
3870 notifyIfacesChangedForNetworkStats();
3871 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
3872 // by other networks that are already connected. Perhaps that can be done by
3873 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
3874 // of rematchAllNetworksAndRequests
3875 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
3876 mKeepaliveTracker.handleStopAllKeepalives(nai, SocketKeepalive.ERROR_INVALID_NETWORK);
3877
3878 mQosCallbackTracker.handleNetworkReleased(nai.network);
3879 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
3880 // Disable wakeup packet monitoring for each interface.
3881 wakeupModifyInterface(iface, nai.networkCapabilities, false);
3882 }
3883 nai.networkMonitor().notifyNetworkDisconnected();
3884 mNetworkAgentInfos.remove(nai);
3885 nai.clatd.update();
3886 synchronized (mNetworkForNetId) {
3887 // Remove the NetworkAgent, but don't mark the netId as
3888 // available until we've told netd to delete it below.
3889 mNetworkForNetId.remove(nai.network.getNetId());
3890 }
3891 propagateUnderlyingNetworkCapabilities(nai.network);
3892 // Remove all previously satisfied requests.
3893 for (int i = 0; i < nai.numNetworkRequests(); i++) {
3894 final NetworkRequest request = nai.requestAt(i);
3895 final NetworkRequestInfo nri = mNetworkRequests.get(request);
3896 final NetworkAgentInfo currentNetwork = nri.getSatisfier();
3897 if (currentNetwork != null
3898 && currentNetwork.network.getNetId() == nai.network.getNetId()) {
3899 // uid rules for this network will be removed in destroyNativeNetwork(nai).
3900 // TODO : setting the satisfier is in fact the job of the rematch. Teach the
3901 // rematch not to keep disconnected agents instead of setting it here ; this
3902 // will also allow removing updating the offers below.
3903 nri.setSatisfier(null, null);
3904 for (final NetworkOfferInfo noi : mNetworkOffers) {
3905 informOffer(nri, noi.offer, mNetworkRanker);
3906 }
3907
3908 if (mDefaultRequest == nri) {
3909 // TODO : make battery stats aware that since 2013 multiple interfaces may be
3910 // active at the same time. For now keep calling this with the default
3911 // network, because while incorrect this is the closest to the old (also
3912 // incorrect) behavior.
3913 mNetworkActivityTracker.updateDataActivityTracking(
3914 null /* newNetwork */, nai);
3915 ensureNetworkTransitionWakelock(nai.toShortString());
3916 }
3917 }
3918 }
3919 nai.clearInactivityState();
3920 // TODO: mLegacyTypeTracker.remove seems redundant given there's a full rematch right after.
3921 // Currently, deleting it breaks tests that check for the default network disconnecting.
3922 // Find out why, fix the rematch code, and delete this.
3923 mLegacyTypeTracker.remove(nai, wasDefault);
3924 rematchAllNetworksAndRequests();
3925 mLingerMonitor.noteDisconnect(nai);
3926
3927 // Immediate teardown.
3928 if (nai.teardownDelayMs == 0) {
3929 destroyNetwork(nai);
3930 return;
3931 }
3932
3933 // Delayed teardown.
3934 try {
3935 mNetd.networkSetPermissionForNetwork(nai.network.netId, INetd.PERMISSION_SYSTEM);
3936 } catch (RemoteException e) {
3937 Log.d(TAG, "Error marking network restricted during teardown: " + e);
3938 }
3939 mHandler.postDelayed(() -> destroyNetwork(nai), nai.teardownDelayMs);
3940 }
3941
3942 private void destroyNetwork(NetworkAgentInfo nai) {
3943 if (nai.created) {
3944 // Tell netd to clean up the configuration for this network
3945 // (routing rules, DNS, etc).
3946 // This may be slow as it requires a lot of netd shelling out to ip and
3947 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
3948 // after we've rematched networks with requests (which might change the default
3949 // network or service a new request from an app), so network traffic isn't interrupted
3950 // for an unnecessarily long time.
3951 destroyNativeNetwork(nai);
3952 mDnsManager.removeNetwork(nai.network);
3953 }
3954 mNetIdManager.releaseNetId(nai.network.getNetId());
3955 nai.onNetworkDestroyed();
3956 }
3957
3958 private boolean createNativeNetwork(@NonNull NetworkAgentInfo nai) {
3959 try {
3960 // This should never fail. Specifying an already in use NetID will cause failure.
3961 final NativeNetworkConfig config;
3962 if (nai.isVPN()) {
3963 if (getVpnType(nai) == VpnManager.TYPE_VPN_NONE) {
3964 Log.wtf(TAG, "Unable to get VPN type from network " + nai.toShortString());
3965 return false;
3966 }
3967 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.VIRTUAL,
3968 INetd.PERMISSION_NONE,
3969 (nai.networkAgentConfig == null || !nai.networkAgentConfig.allowBypass),
3970 getVpnType(nai));
3971 } else {
3972 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.PHYSICAL,
3973 getNetworkPermission(nai.networkCapabilities), /*secure=*/ false,
3974 VpnManager.TYPE_VPN_NONE);
3975 }
3976 mNetd.networkCreate(config);
3977 mDnsResolver.createNetworkCache(nai.network.getNetId());
3978 mDnsManager.updateTransportsForNetwork(nai.network.getNetId(),
3979 nai.networkCapabilities.getTransportTypes());
3980 return true;
3981 } catch (RemoteException | ServiceSpecificException e) {
3982 loge("Error creating network " + nai.toShortString() + ": " + e.getMessage());
3983 return false;
3984 }
3985 }
3986
3987 private void destroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
3988 try {
3989 mNetd.networkDestroy(nai.network.getNetId());
3990 } catch (RemoteException | ServiceSpecificException e) {
3991 loge("Exception destroying network(networkDestroy): " + e);
3992 }
3993 try {
3994 mDnsResolver.destroyNetworkCache(nai.network.getNetId());
3995 } catch (RemoteException | ServiceSpecificException e) {
3996 loge("Exception destroying network: " + e);
3997 }
3998 }
3999
4000 // If this method proves to be too slow then we can maintain a separate
4001 // pendingIntent => NetworkRequestInfo map.
4002 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
4003 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
4004 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
4005 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
4006 if (existingPendingIntent != null &&
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09004007 mDeps.intentFilterEquals(existingPendingIntent, pendingIntent)) {
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00004008 return entry.getValue();
4009 }
4010 }
4011 return null;
4012 }
4013
4014 private void handleRegisterNetworkRequestWithIntent(@NonNull final Message msg) {
4015 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
4016 // handleRegisterNetworkRequestWithIntent() doesn't apply to multilayer requests.
4017 ensureNotMultilayerRequest(nri, "handleRegisterNetworkRequestWithIntent");
4018 final NetworkRequestInfo existingRequest =
4019 findExistingNetworkRequestInfo(nri.mPendingIntent);
4020 if (existingRequest != null) { // remove the existing request.
4021 if (DBG) {
4022 log("Replacing " + existingRequest.mRequests.get(0) + " with "
4023 + nri.mRequests.get(0) + " because their intents matched.");
4024 }
4025 handleReleaseNetworkRequest(existingRequest.mRequests.get(0), mDeps.getCallingUid(),
4026 /* callOnUnavailable */ false);
4027 }
4028 handleRegisterNetworkRequest(nri);
4029 }
4030
4031 private void handleRegisterNetworkRequest(@NonNull final NetworkRequestInfo nri) {
4032 handleRegisterNetworkRequests(Collections.singleton(nri));
4033 }
4034
4035 private void handleRegisterNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
4036 ensureRunningOnConnectivityServiceThread();
4037 for (final NetworkRequestInfo nri : nris) {
4038 mNetworkRequestInfoLogs.log("REGISTER " + nri);
4039 for (final NetworkRequest req : nri.mRequests) {
4040 mNetworkRequests.put(req, nri);
4041 // TODO: Consider update signal strength for other types.
4042 if (req.isListen()) {
4043 for (final NetworkAgentInfo network : mNetworkAgentInfos) {
4044 if (req.networkCapabilities.hasSignalStrength()
4045 && network.satisfiesImmutableCapabilitiesOf(req)) {
4046 updateSignalStrengthThresholds(network, "REGISTER", req);
4047 }
4048 }
4049 }
4050 }
4051 // If this NRI has a satisfier already, it is replacing an older request that
4052 // has been removed. Track it.
4053 final NetworkRequest activeRequest = nri.getActiveRequest();
4054 if (null != activeRequest) {
4055 // If there is an active request, then for sure there is a satisfier.
4056 nri.getSatisfier().addRequest(activeRequest);
4057 }
4058 }
4059
4060 rematchAllNetworksAndRequests();
4061
4062 // Requests that have not been matched to a network will not have been sent to the
4063 // providers, because the old satisfier and the new satisfier are the same (null in this
4064 // case). Send these requests to the providers.
4065 for (final NetworkRequestInfo nri : nris) {
4066 for (final NetworkOfferInfo noi : mNetworkOffers) {
4067 informOffer(nri, noi.offer, mNetworkRanker);
4068 }
4069 }
4070 }
4071
4072 private void handleReleaseNetworkRequestWithIntent(@NonNull final PendingIntent pendingIntent,
4073 final int callingUid) {
4074 final NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
4075 if (nri != null) {
4076 // handleReleaseNetworkRequestWithIntent() paths don't apply to multilayer requests.
4077 ensureNotMultilayerRequest(nri, "handleReleaseNetworkRequestWithIntent");
4078 handleReleaseNetworkRequest(
4079 nri.mRequests.get(0),
4080 callingUid,
4081 /* callOnUnavailable */ false);
4082 }
4083 }
4084
4085 // Determines whether the network is the best (or could become the best, if it validated), for
4086 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
4087 // on the value of reason:
4088 //
4089 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
4090 // then it should be torn down.
4091 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
4092 // then it should be lingered.
4093 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
4094 ensureRunningOnConnectivityServiceThread();
4095
4096 if (!nai.everConnected || nai.isVPN() || nai.isInactive()
4097 || nai.getScore().getKeepConnectedReason() != NetworkScore.KEEP_CONNECTED_NONE) {
4098 return false;
4099 }
4100
4101 final int numRequests;
4102 switch (reason) {
4103 case TEARDOWN:
4104 numRequests = nai.numRequestNetworkRequests();
4105 break;
4106 case LINGER:
4107 numRequests = nai.numForegroundNetworkRequests();
4108 break;
4109 default:
4110 Log.wtf(TAG, "Invalid reason. Cannot happen.");
4111 return true;
4112 }
4113
4114 if (numRequests > 0) return false;
4115
4116 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4117 if (reason == UnneededFor.LINGER
4118 && !nri.isMultilayerRequest()
4119 && nri.mRequests.get(0).isBackgroundRequest()) {
4120 // Background requests don't affect lingering.
4121 continue;
4122 }
4123
4124 if (isNetworkPotentialSatisfier(nai, nri)) {
4125 return false;
4126 }
4127 }
4128 return true;
4129 }
4130
4131 private boolean isNetworkPotentialSatisfier(
4132 @NonNull final NetworkAgentInfo candidate, @NonNull final NetworkRequestInfo nri) {
4133 // listen requests won't keep up a network satisfying it. If this is not a multilayer
4134 // request, return immediately. For multilayer requests, check to see if any of the
4135 // multilayer requests may have a potential satisfier.
4136 if (!nri.isMultilayerRequest() && (nri.mRequests.get(0).isListen()
4137 || nri.mRequests.get(0).isListenForBest())) {
4138 return false;
4139 }
4140 for (final NetworkRequest req : nri.mRequests) {
4141 // This multilayer listen request is satisfied therefore no further requests need to be
4142 // evaluated deeming this network not a potential satisfier.
4143 if ((req.isListen() || req.isListenForBest()) && nri.getActiveRequest() == req) {
4144 return false;
4145 }
4146 // As non-multilayer listen requests have already returned, the below would only happen
4147 // for a multilayer request therefore continue to the next request if available.
4148 if (req.isListen() || req.isListenForBest()) {
4149 continue;
4150 }
4151 // If this Network is already the highest scoring Network for a request, or if
4152 // there is hope for it to become one if it validated, then it is needed.
4153 if (candidate.satisfies(req)) {
4154 // As soon as a network is found that satisfies a request, return. Specifically for
4155 // multilayer requests, returning as soon as a NetworkAgentInfo satisfies a request
4156 // is important so as to not evaluate lower priority requests further in
4157 // nri.mRequests.
4158 final NetworkAgentInfo champion = req.equals(nri.getActiveRequest())
4159 ? nri.getSatisfier() : null;
4160 // Note that this catches two important cases:
4161 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
4162 // is currently satisfying the request. This is desirable when
4163 // cellular ends up validating but WiFi does not.
4164 // 2. Unvalidated WiFi will not be reaped when validated cellular
4165 // is currently satisfying the request. This is desirable when
4166 // WiFi ends up validating and out scoring cellular.
4167 return mNetworkRanker.mightBeat(req, champion, candidate.getValidatedScoreable());
4168 }
4169 }
4170
4171 return false;
4172 }
4173
4174 private NetworkRequestInfo getNriForAppRequest(
4175 NetworkRequest request, int callingUid, String requestedOperation) {
4176 // Looking up the app passed param request in mRequests isn't possible since it may return
4177 // null for a request managed by a per-app default. Therefore use getNriForAppRequest() to
4178 // do the lookup since that will also find per-app default managed requests.
4179 // Additionally, this lookup needs to be relatively fast (hence the lookup optimization)
4180 // to avoid potential race conditions when validating a package->uid mapping when sending
4181 // the callback on the very low-chance that an application shuts down prior to the callback
4182 // being sent.
4183 final NetworkRequestInfo nri = mNetworkRequests.get(request) != null
4184 ? mNetworkRequests.get(request) : getNriForAppRequest(request);
4185
4186 if (nri != null) {
4187 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
4188 log(String.format("UID %d attempted to %s for unowned request %s",
4189 callingUid, requestedOperation, nri));
4190 return null;
4191 }
4192 }
4193
4194 return nri;
4195 }
4196
4197 private void ensureNotMultilayerRequest(@NonNull final NetworkRequestInfo nri,
4198 final String callingMethod) {
4199 if (nri.isMultilayerRequest()) {
4200 throw new IllegalStateException(
4201 callingMethod + " does not support multilayer requests.");
4202 }
4203 }
4204
4205 private void handleTimedOutNetworkRequest(@NonNull final NetworkRequestInfo nri) {
4206 ensureRunningOnConnectivityServiceThread();
4207 // handleTimedOutNetworkRequest() is part of the requestNetwork() flow which works off of a
4208 // single NetworkRequest and thus does not apply to multilayer requests.
4209 ensureNotMultilayerRequest(nri, "handleTimedOutNetworkRequest");
4210 if (mNetworkRequests.get(nri.mRequests.get(0)) == null) {
4211 return;
4212 }
4213 if (nri.isBeingSatisfied()) {
4214 return;
4215 }
4216 if (VDBG || (DBG && nri.mRequests.get(0).isRequest())) {
4217 log("releasing " + nri.mRequests.get(0) + " (timeout)");
4218 }
4219 handleRemoveNetworkRequest(nri);
4220 callCallbackForRequest(
4221 nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
4222 }
4223
4224 private void handleReleaseNetworkRequest(@NonNull final NetworkRequest request,
4225 final int callingUid,
4226 final boolean callOnUnavailable) {
4227 final NetworkRequestInfo nri =
4228 getNriForAppRequest(request, callingUid, "release NetworkRequest");
4229 if (nri == null) {
4230 return;
4231 }
4232 if (VDBG || (DBG && request.isRequest())) {
4233 log("releasing " + request + " (release request)");
4234 }
4235 handleRemoveNetworkRequest(nri);
4236 if (callOnUnavailable) {
4237 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
4238 }
4239 }
4240
4241 private void handleRemoveNetworkRequest(@NonNull final NetworkRequestInfo nri) {
4242 ensureRunningOnConnectivityServiceThread();
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00004243 for (final NetworkRequest req : nri.mRequests) {
James Mattis8f036802021-06-20 16:26:01 -07004244 if (null == mNetworkRequests.remove(req)) {
4245 logw("Attempted removal of untracked request " + req + " for nri " + nri);
4246 continue;
4247 }
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00004248 if (req.isListen()) {
4249 removeListenRequestFromNetworks(req);
4250 }
4251 }
James Mattis8f036802021-06-20 16:26:01 -07004252 nri.unlinkDeathRecipient();
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00004253 if (mDefaultNetworkRequests.remove(nri)) {
4254 // If this request was one of the defaults, then the UID rules need to be updated
4255 // WARNING : if the app(s) for which this network request is the default are doing
4256 // traffic, this will kill their connected sockets, even if an equivalent request
4257 // is going to be reinstated right away ; unconnected traffic will go on the default
4258 // until the new default is set, which will happen very soon.
4259 // TODO : The only way out of this is to diff old defaults and new defaults, and only
4260 // remove ranges for those requests that won't have a replacement
4261 final NetworkAgentInfo satisfier = nri.getSatisfier();
4262 if (null != satisfier) {
4263 try {
paulhude2a2392021-06-09 16:11:35 +08004264 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
4265 satisfier.network.getNetId(),
4266 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08004267 nri.getPreferenceOrderForNetd()));
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00004268 } catch (RemoteException e) {
4269 loge("Exception setting network preference default network", e);
4270 }
4271 }
4272 }
4273 nri.decrementRequestCount();
4274 mNetworkRequestInfoLogs.log("RELEASE " + nri);
4275
4276 if (null != nri.getActiveRequest()) {
4277 if (!nri.getActiveRequest().isListen()) {
4278 removeSatisfiedNetworkRequestFromNetwork(nri);
4279 } else {
4280 nri.setSatisfier(null, null);
4281 }
4282 }
4283
4284 // For all outstanding offers, cancel any of the layers of this NRI that used to be
4285 // needed for this offer.
4286 for (final NetworkOfferInfo noi : mNetworkOffers) {
4287 for (final NetworkRequest req : nri.mRequests) {
4288 if (req.isRequest() && noi.offer.neededFor(req)) {
4289 noi.offer.onNetworkUnneeded(req);
4290 }
4291 }
4292 }
4293 }
4294
4295 private void handleRemoveNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
4296 for (final NetworkRequestInfo nri : nris) {
4297 if (mDefaultRequest == nri) {
4298 // Make sure we never remove the default request.
4299 continue;
4300 }
4301 handleRemoveNetworkRequest(nri);
4302 }
4303 }
4304
4305 private void removeListenRequestFromNetworks(@NonNull final NetworkRequest req) {
4306 // listens don't have a singular affected Network. Check all networks to see
4307 // if this listen request applies and remove it.
4308 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
4309 nai.removeRequest(req.requestId);
4310 if (req.networkCapabilities.hasSignalStrength()
4311 && nai.satisfiesImmutableCapabilitiesOf(req)) {
4312 updateSignalStrengthThresholds(nai, "RELEASE", req);
4313 }
4314 }
4315 }
4316
4317 /**
4318 * Remove a NetworkRequestInfo's satisfied request from its 'satisfier' (NetworkAgentInfo) and
4319 * manage the necessary upkeep (linger, teardown networks, etc.) when doing so.
4320 * @param nri the NetworkRequestInfo to disassociate from its current NetworkAgentInfo
4321 */
4322 private void removeSatisfiedNetworkRequestFromNetwork(@NonNull final NetworkRequestInfo nri) {
4323 boolean wasKept = false;
4324 final NetworkAgentInfo nai = nri.getSatisfier();
4325 if (nai != null) {
4326 final int requestLegacyType = nri.getActiveRequest().legacyType;
4327 final boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
4328 nai.removeRequest(nri.getActiveRequest().requestId);
4329 if (VDBG || DDBG) {
4330 log(" Removing from current network " + nai.toShortString()
4331 + ", leaving " + nai.numNetworkRequests() + " requests.");
4332 }
4333 // If there are still lingered requests on this network, don't tear it down,
4334 // but resume lingering instead.
4335 final long now = SystemClock.elapsedRealtime();
4336 if (updateInactivityState(nai, now)) {
4337 notifyNetworkLosing(nai, now);
4338 }
4339 if (unneeded(nai, UnneededFor.TEARDOWN)) {
4340 if (DBG) log("no live requests for " + nai.toShortString() + "; disconnecting");
4341 teardownUnneededNetwork(nai);
4342 } else {
4343 wasKept = true;
4344 }
4345 nri.setSatisfier(null, null);
4346 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
4347 // Went from foreground to background.
4348 updateCapabilitiesForNetwork(nai);
4349 }
4350
4351 // Maintain the illusion. When this request arrived, we might have pretended
4352 // that a network connected to serve it, even though the network was already
4353 // connected. Now that this request has gone away, we might have to pretend
4354 // that the network disconnected. LegacyTypeTracker will generate that
4355 // phantom disconnect for this type.
4356 if (requestLegacyType != TYPE_NONE) {
4357 boolean doRemove = true;
4358 if (wasKept) {
4359 // check if any of the remaining requests for this network are for the
4360 // same legacy type - if so, don't remove the nai
4361 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4362 NetworkRequest otherRequest = nai.requestAt(i);
4363 if (otherRequest.legacyType == requestLegacyType
4364 && otherRequest.isRequest()) {
4365 if (DBG) log(" still have other legacy request - leaving");
4366 doRemove = false;
4367 }
4368 }
4369 }
4370
4371 if (doRemove) {
4372 mLegacyTypeTracker.remove(requestLegacyType, nai, false);
4373 }
4374 }
4375 }
4376 }
4377
4378 private PerUidCounter getRequestCounter(NetworkRequestInfo nri) {
4379 return checkAnyPermissionOf(
4380 nri.mPid, nri.mUid, NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
4381 ? mSystemNetworkRequestCounter : mNetworkRequestCounter;
4382 }
4383
4384 @Override
4385 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
4386 enforceNetworkStackSettingsOrSetup();
4387 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
4388 encodeBool(accept), encodeBool(always), network));
4389 }
4390
4391 @Override
4392 public void setAcceptPartialConnectivity(Network network, boolean accept, boolean always) {
4393 enforceNetworkStackSettingsOrSetup();
4394 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY,
4395 encodeBool(accept), encodeBool(always), network));
4396 }
4397
4398 @Override
4399 public void setAvoidUnvalidated(Network network) {
4400 enforceNetworkStackSettingsOrSetup();
4401 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
4402 }
4403
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08004404 @Override
4405 public void setTestAllowBadWifiUntil(long timeMs) {
4406 enforceSettingsPermission();
4407 if (!Build.isDebuggable()) {
4408 throw new IllegalStateException("Does not support in non-debuggable build");
4409 }
4410
4411 if (timeMs > System.currentTimeMillis() + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS) {
4412 throw new IllegalArgumentException("It should not exceed "
4413 + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS + "ms from now");
4414 }
4415
4416 mHandler.sendMessage(
4417 mHandler.obtainMessage(EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL, timeMs));
4418 }
4419
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00004420 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
4421 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
4422 " accept=" + accept + " always=" + always);
4423
4424 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4425 if (nai == null) {
4426 // Nothing to do.
4427 return;
4428 }
4429
4430 if (nai.everValidated) {
4431 // The network validated while the dialog box was up. Take no action.
4432 return;
4433 }
4434
4435 if (!nai.networkAgentConfig.explicitlySelected) {
4436 Log.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
4437 }
4438
4439 if (accept != nai.networkAgentConfig.acceptUnvalidated) {
4440 nai.networkAgentConfig.acceptUnvalidated = accept;
4441 // If network becomes partial connectivity and user already accepted to use this
4442 // network, we should respect the user's option and don't need to popup the
4443 // PARTIAL_CONNECTIVITY notification to user again.
4444 nai.networkAgentConfig.acceptPartialConnectivity = accept;
4445 nai.updateScoreForNetworkAgentUpdate();
4446 rematchAllNetworksAndRequests();
4447 }
4448
4449 if (always) {
4450 nai.onSaveAcceptUnvalidated(accept);
4451 }
4452
4453 if (!accept) {
4454 // Tell the NetworkAgent to not automatically reconnect to the network.
4455 nai.onPreventAutomaticReconnect();
4456 // Teardown the network.
4457 teardownUnneededNetwork(nai);
4458 }
4459
4460 }
4461
4462 private void handleSetAcceptPartialConnectivity(Network network, boolean accept,
4463 boolean always) {
4464 if (DBG) {
4465 log("handleSetAcceptPartialConnectivity network=" + network + " accept=" + accept
4466 + " always=" + always);
4467 }
4468
4469 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4470 if (nai == null) {
4471 // Nothing to do.
4472 return;
4473 }
4474
4475 if (nai.lastValidated) {
4476 // The network validated while the dialog box was up. Take no action.
4477 return;
4478 }
4479
4480 if (accept != nai.networkAgentConfig.acceptPartialConnectivity) {
4481 nai.networkAgentConfig.acceptPartialConnectivity = accept;
4482 }
4483
4484 // TODO: Use the current design or save the user choice into IpMemoryStore.
4485 if (always) {
4486 nai.onSaveAcceptUnvalidated(accept);
4487 }
4488
4489 if (!accept) {
4490 // Tell the NetworkAgent to not automatically reconnect to the network.
4491 nai.onPreventAutomaticReconnect();
4492 // Tear down the network.
4493 teardownUnneededNetwork(nai);
4494 } else {
4495 // Inform NetworkMonitor that partial connectivity is acceptable. This will likely
4496 // result in a partial connectivity result which will be processed by
4497 // maybeHandleNetworkMonitorMessage.
4498 //
4499 // TODO: NetworkMonitor does not refer to the "never ask again" bit. The bit is stored
4500 // per network. Therefore, NetworkMonitor may still do https probe.
4501 nai.networkMonitor().setAcceptPartialConnectivity();
4502 }
4503 }
4504
4505 private void handleSetAvoidUnvalidated(Network network) {
4506 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4507 if (nai == null || nai.lastValidated) {
4508 // Nothing to do. The network either disconnected or revalidated.
4509 return;
4510 }
4511 if (!nai.avoidUnvalidated) {
4512 nai.avoidUnvalidated = true;
4513 nai.updateScoreForNetworkAgentUpdate();
4514 rematchAllNetworksAndRequests();
4515 }
4516 }
4517
4518 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
4519 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
4520 mHandler.sendMessageDelayed(
4521 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
4522 PROMPT_UNVALIDATED_DELAY_MS);
4523 }
4524
4525 @Override
4526 public void startCaptivePortalApp(Network network) {
4527 enforceNetworkStackOrSettingsPermission();
4528 mHandler.post(() -> {
4529 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4530 if (nai == null) return;
4531 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
4532 nai.networkMonitor().launchCaptivePortalApp();
4533 });
4534 }
4535
4536 /**
4537 * NetworkStack endpoint to start the captive portal app. The NetworkStack needs to use this
4538 * endpoint as it does not have INTERACT_ACROSS_USERS_FULL itself.
4539 * @param network Network on which the captive portal was detected.
4540 * @param appExtras Bundle to use as intent extras for the captive portal application.
4541 * Must be treated as opaque to avoid preventing the captive portal app to
4542 * update its arguments.
4543 */
4544 @Override
4545 public void startCaptivePortalAppInternal(Network network, Bundle appExtras) {
4546 mContext.enforceCallingOrSelfPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4547 "ConnectivityService");
4548
4549 final Intent appIntent = new Intent(ConnectivityManager.ACTION_CAPTIVE_PORTAL_SIGN_IN);
4550 appIntent.putExtras(appExtras);
4551 appIntent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL,
4552 new CaptivePortal(new CaptivePortalImpl(network).asBinder()));
4553 appIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
4554
4555 final long token = Binder.clearCallingIdentity();
4556 try {
4557 mContext.startActivityAsUser(appIntent, UserHandle.CURRENT);
4558 } finally {
4559 Binder.restoreCallingIdentity(token);
4560 }
4561 }
4562
4563 private class CaptivePortalImpl extends ICaptivePortal.Stub {
4564 private final Network mNetwork;
4565
4566 private CaptivePortalImpl(Network network) {
4567 mNetwork = network;
4568 }
4569
4570 @Override
4571 public void appResponse(final int response) {
4572 if (response == CaptivePortal.APP_RETURN_WANTED_AS_IS) {
4573 enforceSettingsPermission();
4574 }
4575
4576 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
4577 if (nm == null) return;
4578 nm.notifyCaptivePortalAppFinished(response);
4579 }
4580
4581 @Override
4582 public void appRequest(final int request) {
4583 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
4584 if (nm == null) return;
4585
4586 if (request == CaptivePortal.APP_REQUEST_REEVALUATION_REQUIRED) {
4587 checkNetworkStackPermission();
4588 nm.forceReevaluation(mDeps.getCallingUid());
4589 }
4590 }
4591
4592 @Nullable
4593 private NetworkMonitorManager getNetworkMonitorManager(final Network network) {
4594 // getNetworkAgentInfoForNetwork is thread-safe
4595 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4596 if (nai == null) return null;
4597
4598 // nai.networkMonitor() is thread-safe
4599 return nai.networkMonitor();
4600 }
4601 }
4602
4603 public boolean avoidBadWifi() {
4604 return mMultinetworkPolicyTracker.getAvoidBadWifi();
4605 }
4606
4607 /**
4608 * Return whether the device should maintain continuous, working connectivity by switching away
4609 * from WiFi networks having no connectivity.
4610 * @see MultinetworkPolicyTracker#getAvoidBadWifi()
4611 */
4612 public boolean shouldAvoidBadWifi() {
4613 if (!checkNetworkStackPermission()) {
4614 throw new SecurityException("avoidBadWifi requires NETWORK_STACK permission");
4615 }
4616 return avoidBadWifi();
4617 }
4618
4619 private void updateAvoidBadWifi() {
4620 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
4621 nai.updateScoreForNetworkAgentUpdate();
4622 }
4623 rematchAllNetworksAndRequests();
4624 }
4625
4626 // TODO: Evaluate whether this is of interest to other consumers of
4627 // MultinetworkPolicyTracker and worth moving out of here.
4628 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
4629 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
4630 if (!configRestrict) {
4631 pw.println("Bad Wi-Fi avoidance: unrestricted");
4632 return;
4633 }
4634
4635 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
4636 pw.increaseIndent();
4637 pw.println("Config restrict: " + configRestrict);
4638
4639 final String value = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
4640 String description;
4641 // Can't use a switch statement because strings are legal case labels, but null is not.
4642 if ("0".equals(value)) {
4643 description = "get stuck";
4644 } else if (value == null) {
4645 description = "prompt";
4646 } else if ("1".equals(value)) {
4647 description = "avoid";
4648 } else {
4649 description = value + " (?)";
4650 }
4651 pw.println("User setting: " + description);
4652 pw.println("Network overrides:");
4653 pw.increaseIndent();
4654 for (NetworkAgentInfo nai : networksSortedById()) {
4655 if (nai.avoidUnvalidated) {
4656 pw.println(nai.toShortString());
4657 }
4658 }
4659 pw.decreaseIndent();
4660 pw.decreaseIndent();
4661 }
4662
4663 // TODO: This method is copied from TetheringNotificationUpdater. Should have a utility class to
4664 // unify the method.
4665 private static @NonNull String getSettingsPackageName(@NonNull final PackageManager pm) {
4666 final Intent settingsIntent = new Intent(Settings.ACTION_SETTINGS);
4667 final ComponentName settingsComponent = settingsIntent.resolveActivity(pm);
4668 return settingsComponent != null
4669 ? settingsComponent.getPackageName() : "com.android.settings";
4670 }
4671
4672 private void showNetworkNotification(NetworkAgentInfo nai, NotificationType type) {
4673 final String action;
4674 final boolean highPriority;
4675 switch (type) {
4676 case NO_INTERNET:
4677 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
4678 // High priority because it is only displayed for explicitly selected networks.
4679 highPriority = true;
4680 break;
4681 case PRIVATE_DNS_BROKEN:
4682 action = Settings.ACTION_WIRELESS_SETTINGS;
4683 // High priority because we should let user know why there is no internet.
4684 highPriority = true;
4685 break;
4686 case LOST_INTERNET:
4687 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
4688 // High priority because it could help the user avoid unexpected data usage.
4689 highPriority = true;
4690 break;
4691 case PARTIAL_CONNECTIVITY:
4692 action = ConnectivityManager.ACTION_PROMPT_PARTIAL_CONNECTIVITY;
4693 // Don't bother the user with a high-priority notification if the network was not
4694 // explicitly selected by the user.
4695 highPriority = nai.networkAgentConfig.explicitlySelected;
4696 break;
4697 default:
4698 Log.wtf(TAG, "Unknown notification type " + type);
4699 return;
4700 }
4701
4702 Intent intent = new Intent(action);
4703 if (type != NotificationType.PRIVATE_DNS_BROKEN) {
4704 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, nai.network);
4705 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4706 // Some OEMs have their own Settings package. Thus, need to get the current using
4707 // Settings package name instead of just use default name "com.android.settings".
4708 final String settingsPkgName = getSettingsPackageName(mContext.getPackageManager());
4709 intent.setClassName(settingsPkgName,
4710 settingsPkgName + ".wifi.WifiNoInternetDialog");
4711 }
4712
4713 PendingIntent pendingIntent = PendingIntent.getActivity(
4714 mContext.createContextAsUser(UserHandle.CURRENT, 0 /* flags */),
4715 0 /* requestCode */,
4716 intent,
4717 PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE);
4718
4719 mNotifier.showNotification(
4720 nai.network.getNetId(), type, nai, null, pendingIntent, highPriority);
4721 }
4722
4723 private boolean shouldPromptUnvalidated(NetworkAgentInfo nai) {
4724 // Don't prompt if the network is validated, and don't prompt on captive portals
4725 // because we're already prompting the user to sign in.
4726 if (nai.everValidated || nai.everCaptivePortalDetected) {
4727 return false;
4728 }
4729
4730 // If a network has partial connectivity, always prompt unless the user has already accepted
4731 // partial connectivity and selected don't ask again. This ensures that if the device
4732 // automatically connects to a network that has partial Internet access, the user will
4733 // always be able to use it, either because they've already chosen "don't ask again" or
4734 // because we have prompt them.
4735 if (nai.partialConnectivity && !nai.networkAgentConfig.acceptPartialConnectivity) {
4736 return true;
4737 }
4738
4739 // If a network has no Internet access, only prompt if the network was explicitly selected
4740 // and if the user has not already told us to use the network regardless of whether it
4741 // validated or not.
4742 if (nai.networkAgentConfig.explicitlySelected
4743 && !nai.networkAgentConfig.acceptUnvalidated) {
4744 return true;
4745 }
4746
4747 return false;
4748 }
4749
4750 private void handlePromptUnvalidated(Network network) {
4751 if (VDBG || DDBG) log("handlePromptUnvalidated " + network);
4752 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4753
4754 if (nai == null || !shouldPromptUnvalidated(nai)) {
4755 return;
4756 }
4757
4758 // Stop automatically reconnecting to this network in the future. Automatically connecting
4759 // to a network that provides no or limited connectivity is not useful, because the user
4760 // cannot use that network except through the notification shown by this method, and the
4761 // notification is only shown if the network is explicitly selected by the user.
4762 nai.onPreventAutomaticReconnect();
4763
4764 // TODO: Evaluate if it's needed to wait 8 seconds for triggering notification when
4765 // NetworkMonitor detects the network is partial connectivity. Need to change the design to
4766 // popup the notification immediately when the network is partial connectivity.
4767 if (nai.partialConnectivity) {
4768 showNetworkNotification(nai, NotificationType.PARTIAL_CONNECTIVITY);
4769 } else {
4770 showNetworkNotification(nai, NotificationType.NO_INTERNET);
4771 }
4772 }
4773
4774 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
4775 NetworkCapabilities nc = nai.networkCapabilities;
4776 if (DBG) log("handleNetworkUnvalidated " + nai.toShortString() + " cap=" + nc);
4777
4778 if (!nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
4779 return;
4780 }
4781
4782 if (mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
4783 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
4784 }
4785 }
4786
4787 @Override
4788 public int getMultipathPreference(Network network) {
4789 enforceAccessPermission();
4790
4791 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4792 if (nai != null && nai.networkCapabilities
4793 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
4794 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
4795 }
4796
4797 final NetworkPolicyManager netPolicyManager =
4798 mContext.getSystemService(NetworkPolicyManager.class);
4799
4800 final long token = Binder.clearCallingIdentity();
4801 final int networkPreference;
4802 try {
4803 networkPreference = netPolicyManager.getMultipathPreference(network);
4804 } finally {
4805 Binder.restoreCallingIdentity(token);
4806 }
4807 if (networkPreference != 0) {
4808 return networkPreference;
4809 }
4810 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
4811 }
4812
4813 @Override
4814 public NetworkRequest getDefaultRequest() {
4815 return mDefaultRequest.mRequests.get(0);
4816 }
4817
4818 private class InternalHandler extends Handler {
4819 public InternalHandler(Looper looper) {
4820 super(looper);
4821 }
4822
4823 @Override
4824 public void handleMessage(Message msg) {
4825 switch (msg.what) {
4826 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
4827 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
4828 handleReleaseNetworkTransitionWakelock(msg.what);
4829 break;
4830 }
4831 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
4832 mProxyTracker.loadDeprecatedGlobalHttpProxy();
4833 break;
4834 }
4835 case EVENT_PROXY_HAS_CHANGED: {
4836 final Pair<Network, ProxyInfo> arg = (Pair<Network, ProxyInfo>) msg.obj;
4837 handleApplyDefaultProxy(arg.second);
4838 break;
4839 }
4840 case EVENT_REGISTER_NETWORK_PROVIDER: {
4841 handleRegisterNetworkProvider((NetworkProviderInfo) msg.obj);
4842 break;
4843 }
4844 case EVENT_UNREGISTER_NETWORK_PROVIDER: {
4845 handleUnregisterNetworkProvider((Messenger) msg.obj);
4846 break;
4847 }
4848 case EVENT_REGISTER_NETWORK_OFFER: {
4849 handleRegisterNetworkOffer((NetworkOffer) msg.obj);
4850 break;
4851 }
4852 case EVENT_UNREGISTER_NETWORK_OFFER: {
4853 final NetworkOfferInfo offer =
4854 findNetworkOfferInfoByCallback((INetworkOfferCallback) msg.obj);
4855 if (null != offer) {
4856 handleUnregisterNetworkOffer(offer);
4857 }
4858 break;
4859 }
4860 case EVENT_REGISTER_NETWORK_AGENT: {
4861 final Pair<NetworkAgentInfo, INetworkMonitor> arg =
4862 (Pair<NetworkAgentInfo, INetworkMonitor>) msg.obj;
4863 handleRegisterNetworkAgent(arg.first, arg.second);
4864 break;
4865 }
4866 case EVENT_REGISTER_NETWORK_REQUEST:
4867 case EVENT_REGISTER_NETWORK_LISTENER: {
4868 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
4869 break;
4870 }
4871 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
4872 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
4873 handleRegisterNetworkRequestWithIntent(msg);
4874 break;
4875 }
4876 case EVENT_TIMEOUT_NETWORK_REQUEST: {
4877 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
4878 handleTimedOutNetworkRequest(nri);
4879 break;
4880 }
4881 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
4882 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
4883 break;
4884 }
4885 case EVENT_RELEASE_NETWORK_REQUEST: {
4886 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1,
4887 /* callOnUnavailable */ false);
4888 break;
4889 }
4890 case EVENT_SET_ACCEPT_UNVALIDATED: {
4891 Network network = (Network) msg.obj;
4892 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
4893 break;
4894 }
4895 case EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY: {
4896 Network network = (Network) msg.obj;
4897 handleSetAcceptPartialConnectivity(network, toBool(msg.arg1),
4898 toBool(msg.arg2));
4899 break;
4900 }
4901 case EVENT_SET_AVOID_UNVALIDATED: {
4902 handleSetAvoidUnvalidated((Network) msg.obj);
4903 break;
4904 }
4905 case EVENT_PROMPT_UNVALIDATED: {
4906 handlePromptUnvalidated((Network) msg.obj);
4907 break;
4908 }
4909 case EVENT_CONFIGURE_ALWAYS_ON_NETWORKS: {
4910 handleConfigureAlwaysOnNetworks();
4911 break;
4912 }
4913 // Sent by KeepaliveTracker to process an app request on the state machine thread.
4914 case NetworkAgent.CMD_START_SOCKET_KEEPALIVE: {
4915 mKeepaliveTracker.handleStartKeepalive(msg);
4916 break;
4917 }
4918 // Sent by KeepaliveTracker to process an app request on the state machine thread.
4919 case NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE: {
4920 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
4921 int slot = msg.arg1;
4922 int reason = msg.arg2;
4923 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
4924 break;
4925 }
Cody Kestingf1120be2020-08-03 18:01:40 -07004926 case EVENT_REPORT_NETWORK_CONNECTIVITY: {
4927 handleReportNetworkConnectivity((NetworkAgentInfo) msg.obj, msg.arg1,
4928 toBool(msg.arg2));
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00004929 break;
4930 }
4931 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
4932 handlePrivateDnsSettingsChanged();
4933 break;
4934 case EVENT_PRIVATE_DNS_VALIDATION_UPDATE:
4935 handlePrivateDnsValidationUpdate(
4936 (PrivateDnsValidationUpdate) msg.obj);
4937 break;
4938 case EVENT_UID_BLOCKED_REASON_CHANGED:
4939 handleUidBlockedReasonChanged(msg.arg1, msg.arg2);
4940 break;
4941 case EVENT_SET_REQUIRE_VPN_FOR_UIDS:
4942 handleSetRequireVpnForUids(toBool(msg.arg1), (UidRange[]) msg.obj);
4943 break;
4944 case EVENT_SET_OEM_NETWORK_PREFERENCE: {
4945 final Pair<OemNetworkPreferences, IOnCompleteListener> arg =
4946 (Pair<OemNetworkPreferences, IOnCompleteListener>) msg.obj;
4947 handleSetOemNetworkPreference(arg.first, arg.second);
4948 break;
4949 }
4950 case EVENT_SET_PROFILE_NETWORK_PREFERENCE: {
4951 final Pair<ProfileNetworkPreferences.Preference, IOnCompleteListener> arg =
4952 (Pair<ProfileNetworkPreferences.Preference, IOnCompleteListener>)
4953 msg.obj;
4954 handleSetProfileNetworkPreference(arg.first, arg.second);
4955 break;
4956 }
4957 case EVENT_REPORT_NETWORK_ACTIVITY:
4958 mNetworkActivityTracker.handleReportNetworkActivity();
4959 break;
paulhu71ad4f12021-05-25 14:56:27 +08004960 case EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED:
4961 handleMobileDataPreferredUidsChanged();
4962 break;
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08004963 case EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL:
4964 final long timeMs = ((Long) msg.obj).longValue();
4965 mMultinetworkPolicyTracker.setTestAllowBadWifiUntil(timeMs);
4966 break;
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00004967 }
4968 }
4969 }
4970
4971 @Override
4972 @Deprecated
4973 public int getLastTetherError(String iface) {
4974 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
4975 Context.TETHERING_SERVICE);
4976 return tm.getLastTetherError(iface);
4977 }
4978
4979 @Override
4980 @Deprecated
4981 public String[] getTetherableIfaces() {
4982 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
4983 Context.TETHERING_SERVICE);
4984 return tm.getTetherableIfaces();
4985 }
4986
4987 @Override
4988 @Deprecated
4989 public String[] getTetheredIfaces() {
4990 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
4991 Context.TETHERING_SERVICE);
4992 return tm.getTetheredIfaces();
4993 }
4994
4995
4996 @Override
4997 @Deprecated
4998 public String[] getTetheringErroredIfaces() {
4999 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5000 Context.TETHERING_SERVICE);
5001
5002 return tm.getTetheringErroredIfaces();
5003 }
5004
5005 @Override
5006 @Deprecated
5007 public String[] getTetherableUsbRegexs() {
5008 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5009 Context.TETHERING_SERVICE);
5010
5011 return tm.getTetherableUsbRegexs();
5012 }
5013
5014 @Override
5015 @Deprecated
5016 public String[] getTetherableWifiRegexs() {
5017 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5018 Context.TETHERING_SERVICE);
5019 return tm.getTetherableWifiRegexs();
5020 }
5021
5022 // Called when we lose the default network and have no replacement yet.
5023 // This will automatically be cleared after X seconds or a new default network
5024 // becomes CONNECTED, whichever happens first. The timer is started by the
5025 // first caller and not restarted by subsequent callers.
5026 private void ensureNetworkTransitionWakelock(String forWhom) {
5027 synchronized (this) {
5028 if (mNetTransitionWakeLock.isHeld()) {
5029 return;
5030 }
5031 mNetTransitionWakeLock.acquire();
5032 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
5033 mTotalWakelockAcquisitions++;
5034 }
5035 mWakelockLogs.log("ACQUIRE for " + forWhom);
5036 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
5037 final int lockTimeout = mResources.get().getInteger(
5038 R.integer.config_networkTransitionTimeout);
5039 mHandler.sendMessageDelayed(msg, lockTimeout);
5040 }
5041
5042 // Called when we gain a new default network to release the network transition wakelock in a
5043 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
5044 // message is cancelled.
5045 private void scheduleReleaseNetworkTransitionWakelock() {
5046 synchronized (this) {
5047 if (!mNetTransitionWakeLock.isHeld()) {
5048 return; // expiry message released the lock first.
5049 }
5050 }
5051 // Cancel self timeout on wakelock hold.
5052 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
5053 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
5054 mHandler.sendMessageDelayed(msg, 1000);
5055 }
5056
5057 // Called when either message of ensureNetworkTransitionWakelock or
5058 // scheduleReleaseNetworkTransitionWakelock is processed.
5059 private void handleReleaseNetworkTransitionWakelock(int eventId) {
5060 String event = eventName(eventId);
5061 synchronized (this) {
5062 if (!mNetTransitionWakeLock.isHeld()) {
5063 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
5064 Log.w(TAG, "expected Net Transition WakeLock to be held");
5065 return;
5066 }
5067 mNetTransitionWakeLock.release();
5068 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
5069 mTotalWakelockDurationMs += lockDuration;
5070 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
5071 mTotalWakelockReleases++;
5072 }
5073 mWakelockLogs.log(String.format("RELEASE (%s)", event));
5074 }
5075
5076 // 100 percent is full good, 0 is full bad.
5077 @Override
5078 public void reportInetCondition(int networkType, int percentage) {
5079 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
5080 if (nai == null) return;
5081 reportNetworkConnectivity(nai.network, percentage > 50);
5082 }
5083
5084 @Override
5085 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
5086 enforceAccessPermission();
5087 enforceInternetPermission();
5088 final int uid = mDeps.getCallingUid();
5089 final int connectivityInfo = encodeBool(hasConnectivity);
5090
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00005091 final NetworkAgentInfo nai;
5092 if (network == null) {
5093 nai = getDefaultNetwork();
5094 } else {
5095 nai = getNetworkAgentInfoForNetwork(network);
5096 }
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00005097
5098 mHandler.sendMessage(
Cody Kestingf1120be2020-08-03 18:01:40 -07005099 mHandler.obtainMessage(
5100 EVENT_REPORT_NETWORK_CONNECTIVITY, uid, connectivityInfo, nai));
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00005101 }
5102
5103 private void handleReportNetworkConnectivity(
Cody Kestingf1120be2020-08-03 18:01:40 -07005104 @Nullable NetworkAgentInfo nai, int uid, boolean hasConnectivity) {
Cody Kestingf1120be2020-08-03 18:01:40 -07005105 if (nai == null
5106 || nai != getNetworkAgentInfoForNetwork(nai.network)
Cody Kestingf1120be2020-08-03 18:01:40 -07005107 || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00005108 return;
5109 }
5110 // Revalidate if the app report does not match our current validated state.
5111 if (hasConnectivity == nai.lastValidated) {
Cody Kestingf1120be2020-08-03 18:01:40 -07005112 mConnectivityDiagnosticsHandler.sendMessage(
5113 mConnectivityDiagnosticsHandler.obtainMessage(
5114 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
5115 new ReportedNetworkConnectivityInfo(
5116 hasConnectivity, false /* isNetworkRevalidating */, uid, nai)));
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00005117 return;
5118 }
5119 if (DBG) {
5120 int netid = nai.network.getNetId();
5121 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
5122 }
5123 // Validating a network that has not yet connected could result in a call to
5124 // rematchNetworkAndRequests() which is not meant to work on such networks.
5125 if (!nai.everConnected) {
5126 return;
5127 }
5128 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
5129 if (isNetworkWithCapabilitiesBlocked(nc, uid, false)) {
5130 return;
5131 }
Cody Kestingf1120be2020-08-03 18:01:40 -07005132
5133 // Send CONNECTIVITY_REPORTED event before re-validating the Network to force an ordering of
5134 // ConnDiags events. This ensures that #onNetworkConnectivityReported() will be called
5135 // before #onConnectivityReportAvailable(), which is called once Network evaluation is
5136 // completed.
5137 mConnectivityDiagnosticsHandler.sendMessage(
5138 mConnectivityDiagnosticsHandler.obtainMessage(
5139 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
5140 new ReportedNetworkConnectivityInfo(
5141 hasConnectivity, true /* isNetworkRevalidating */, uid, nai)));
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00005142 nai.networkMonitor().forceReevaluation(uid);
5143 }
5144
5145 // TODO: call into netd.
5146 private boolean queryUserAccess(int uid, Network network) {
5147 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5148 if (nai == null) return false;
5149
5150 // Any UID can use its default network.
5151 if (nai == getDefaultNetworkForUid(uid)) return true;
5152
5153 // Privileged apps can use any network.
5154 if (mPermissionMonitor.hasRestrictedNetworksPermission(uid)) {
5155 return true;
5156 }
5157
5158 // An unprivileged UID can use a VPN iff the VPN applies to it.
5159 if (nai.isVPN()) {
5160 return nai.networkCapabilities.appliesToUid(uid);
5161 }
5162
5163 // An unprivileged UID can bypass the VPN that applies to it only if it can protect its
5164 // sockets, i.e., if it is the owner.
5165 final NetworkAgentInfo vpn = getVpnForUid(uid);
5166 if (vpn != null && !vpn.networkAgentConfig.allowBypass
5167 && uid != vpn.networkCapabilities.getOwnerUid()) {
5168 return false;
5169 }
5170
5171 // The UID's permission must be at least sufficient for the network. Since the restricted
5172 // permission was already checked above, that just leaves background networks.
5173 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
5174 return mPermissionMonitor.hasUseBackgroundNetworksPermission(uid);
5175 }
5176
5177 // Unrestricted network. Anyone gets to use it.
5178 return true;
5179 }
5180
5181 /**
5182 * Returns information about the proxy a certain network is using. If given a null network, it
5183 * it will return the proxy for the bound network for the caller app or the default proxy if
5184 * none.
5185 *
5186 * @param network the network we want to get the proxy information for.
5187 * @return Proxy information if a network has a proxy configured, or otherwise null.
5188 */
5189 @Override
5190 public ProxyInfo getProxyForNetwork(Network network) {
5191 final ProxyInfo globalProxy = mProxyTracker.getGlobalProxy();
5192 if (globalProxy != null) return globalProxy;
5193 if (network == null) {
5194 // Get the network associated with the calling UID.
5195 final Network activeNetwork = getActiveNetworkForUidInternal(mDeps.getCallingUid(),
5196 true);
5197 if (activeNetwork == null) {
5198 return null;
5199 }
5200 return getLinkPropertiesProxyInfo(activeNetwork);
5201 } else if (mDeps.queryUserAccess(mDeps.getCallingUid(), network, this)) {
5202 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
5203 // caller may not have.
5204 return getLinkPropertiesProxyInfo(network);
5205 }
5206 // No proxy info available if the calling UID does not have network access.
5207 return null;
5208 }
5209
5210
5211 private ProxyInfo getLinkPropertiesProxyInfo(Network network) {
5212 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5213 if (nai == null) return null;
5214 synchronized (nai) {
5215 final ProxyInfo linkHttpProxy = nai.linkProperties.getHttpProxy();
5216 return linkHttpProxy == null ? null : new ProxyInfo(linkHttpProxy);
5217 }
5218 }
5219
5220 @Override
5221 public void setGlobalProxy(@Nullable final ProxyInfo proxyProperties) {
5222 PermissionUtils.enforceNetworkStackPermission(mContext);
5223 mProxyTracker.setGlobalProxy(proxyProperties);
5224 }
5225
5226 @Override
5227 @Nullable
5228 public ProxyInfo getGlobalProxy() {
5229 return mProxyTracker.getGlobalProxy();
5230 }
5231
5232 private void handleApplyDefaultProxy(ProxyInfo proxy) {
5233 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
5234 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
5235 proxy = null;
5236 }
5237 mProxyTracker.setDefaultProxy(proxy);
5238 }
5239
5240 // If the proxy has changed from oldLp to newLp, resend proxy broadcast. This method gets called
5241 // when any network changes proxy.
5242 // TODO: Remove usage of broadcast extras as they are deprecated and not applicable in a
5243 // multi-network world where an app might be bound to a non-default network.
5244 private void updateProxy(LinkProperties newLp, LinkProperties oldLp) {
5245 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
5246 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
5247
5248 if (!ProxyTracker.proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
5249 mProxyTracker.sendProxyBroadcast();
5250 }
5251 }
5252
5253 private static class SettingsObserver extends ContentObserver {
5254 final private HashMap<Uri, Integer> mUriEventMap;
5255 final private Context mContext;
5256 final private Handler mHandler;
5257
5258 SettingsObserver(Context context, Handler handler) {
5259 super(null);
5260 mUriEventMap = new HashMap<>();
5261 mContext = context;
5262 mHandler = handler;
5263 }
5264
5265 void observe(Uri uri, int what) {
5266 mUriEventMap.put(uri, what);
5267 final ContentResolver resolver = mContext.getContentResolver();
5268 resolver.registerContentObserver(uri, false, this);
5269 }
5270
5271 @Override
5272 public void onChange(boolean selfChange) {
5273 Log.wtf(TAG, "Should never be reached.");
5274 }
5275
5276 @Override
5277 public void onChange(boolean selfChange, Uri uri) {
5278 final Integer what = mUriEventMap.get(uri);
5279 if (what != null) {
5280 mHandler.obtainMessage(what).sendToTarget();
5281 } else {
5282 loge("No matching event to send for URI=" + uri);
5283 }
5284 }
5285 }
5286
5287 private static void log(String s) {
5288 Log.d(TAG, s);
5289 }
5290
5291 private static void logw(String s) {
5292 Log.w(TAG, s);
5293 }
5294
5295 private static void logwtf(String s) {
5296 Log.wtf(TAG, s);
5297 }
5298
5299 private static void logwtf(String s, Throwable t) {
5300 Log.wtf(TAG, s, t);
5301 }
5302
5303 private static void loge(String s) {
5304 Log.e(TAG, s);
5305 }
5306
5307 private static void loge(String s, Throwable t) {
5308 Log.e(TAG, s, t);
5309 }
5310
5311 /**
5312 * Return the information of all ongoing VPNs.
5313 *
5314 * <p>This method is used to update NetworkStatsService.
5315 *
5316 * <p>Must be called on the handler thread.
5317 */
5318 private UnderlyingNetworkInfo[] getAllVpnInfo() {
5319 ensureRunningOnConnectivityServiceThread();
5320 if (mLockdownEnabled) {
5321 return new UnderlyingNetworkInfo[0];
5322 }
5323 List<UnderlyingNetworkInfo> infoList = new ArrayList<>();
5324 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
5325 UnderlyingNetworkInfo info = createVpnInfo(nai);
5326 if (info != null) {
5327 infoList.add(info);
5328 }
5329 }
5330 return infoList.toArray(new UnderlyingNetworkInfo[infoList.size()]);
5331 }
5332
5333 /**
5334 * @return VPN information for accounting, or null if we can't retrieve all required
5335 * information, e.g underlying ifaces.
5336 */
5337 private UnderlyingNetworkInfo createVpnInfo(NetworkAgentInfo nai) {
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00005338 Network[] underlyingNetworks = nai.declaredUnderlyingNetworks;
5339 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
5340 // the underlyingNetworks list.
Lorenzo Colittibd079452021-07-02 11:47:57 +09005341 // TODO: stop using propagateUnderlyingCapabilities here, for example, by always
5342 // initializing NetworkAgentInfo#declaredUnderlyingNetworks to an empty array.
5343 if (underlyingNetworks == null && nai.propagateUnderlyingCapabilities()) {
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00005344 final NetworkAgentInfo defaultNai = getDefaultNetworkForUid(
5345 nai.networkCapabilities.getOwnerUid());
5346 if (defaultNai != null) {
5347 underlyingNetworks = new Network[] { defaultNai.network };
5348 }
5349 }
5350
5351 if (CollectionUtils.isEmpty(underlyingNetworks)) return null;
5352
5353 List<String> interfaces = new ArrayList<>();
5354 for (Network network : underlyingNetworks) {
5355 NetworkAgentInfo underlyingNai = getNetworkAgentInfoForNetwork(network);
5356 if (underlyingNai == null) continue;
5357 LinkProperties lp = underlyingNai.linkProperties;
5358 for (String iface : lp.getAllInterfaceNames()) {
5359 if (!TextUtils.isEmpty(iface)) {
5360 interfaces.add(iface);
5361 }
5362 }
5363 }
5364
5365 if (interfaces.isEmpty()) return null;
5366
5367 // Must be non-null or NetworkStatsService will crash.
5368 // Cannot happen in production code because Vpn only registers the NetworkAgent after the
5369 // tun or ipsec interface is created.
5370 // TODO: Remove this check.
5371 if (nai.linkProperties.getInterfaceName() == null) return null;
5372
5373 return new UnderlyingNetworkInfo(nai.networkCapabilities.getOwnerUid(),
5374 nai.linkProperties.getInterfaceName(), interfaces);
5375 }
5376
5377 // TODO This needs to be the default network that applies to the NAI.
5378 private Network[] underlyingNetworksOrDefault(final int ownerUid,
5379 Network[] underlyingNetworks) {
5380 final Network defaultNetwork = getNetwork(getDefaultNetworkForUid(ownerUid));
5381 if (underlyingNetworks == null && defaultNetwork != null) {
5382 // null underlying networks means to track the default.
5383 underlyingNetworks = new Network[] { defaultNetwork };
5384 }
5385 return underlyingNetworks;
5386 }
5387
5388 // Returns true iff |network| is an underlying network of |nai|.
5389 private boolean hasUnderlyingNetwork(NetworkAgentInfo nai, Network network) {
5390 // TODO: support more than one level of underlying networks, either via a fixed-depth search
5391 // (e.g., 2 levels of underlying networks), or via loop detection, or....
Lorenzo Colittibd079452021-07-02 11:47:57 +09005392 if (!nai.propagateUnderlyingCapabilities()) return false;
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00005393 final Network[] underlying = underlyingNetworksOrDefault(
5394 nai.networkCapabilities.getOwnerUid(), nai.declaredUnderlyingNetworks);
5395 return CollectionUtils.contains(underlying, network);
5396 }
5397
5398 /**
5399 * Recompute the capabilities for any networks that had a specific network as underlying.
5400 *
5401 * When underlying networks change, such networks may have to update capabilities to reflect
5402 * things like the metered bit, their transports, and so on. The capabilities are calculated
5403 * immediately. This method runs on the ConnectivityService thread.
5404 */
5405 private void propagateUnderlyingNetworkCapabilities(Network updatedNetwork) {
5406 ensureRunningOnConnectivityServiceThread();
5407 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
5408 if (updatedNetwork == null || hasUnderlyingNetwork(nai, updatedNetwork)) {
5409 updateCapabilitiesForNetwork(nai);
5410 }
5411 }
5412 }
5413
5414 private boolean isUidBlockedByVpn(int uid, List<UidRange> blockedUidRanges) {
5415 // Determine whether this UID is blocked because of always-on VPN lockdown. If a VPN applies
5416 // to the UID, then the UID is not blocked because always-on VPN lockdown applies only when
5417 // a VPN is not up.
5418 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
5419 if (vpnNai != null && !vpnNai.networkAgentConfig.allowBypass) return false;
5420 for (UidRange range : blockedUidRanges) {
5421 if (range.contains(uid)) return true;
5422 }
5423 return false;
5424 }
5425
5426 @Override
5427 public void setRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
5428 enforceNetworkStackOrSettingsPermission();
5429 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_REQUIRE_VPN_FOR_UIDS,
5430 encodeBool(requireVpn), 0 /* arg2 */, ranges));
5431 }
5432
5433 private void handleSetRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
5434 if (DBG) {
5435 Log.d(TAG, "Setting VPN " + (requireVpn ? "" : "not ") + "required for UIDs: "
5436 + Arrays.toString(ranges));
5437 }
5438 // Cannot use a Set since the list of UID ranges might contain duplicates.
5439 final List<UidRange> newVpnBlockedUidRanges = new ArrayList(mVpnBlockedUidRanges);
5440 for (int i = 0; i < ranges.length; i++) {
5441 if (requireVpn) {
5442 newVpnBlockedUidRanges.add(ranges[i]);
5443 } else {
5444 newVpnBlockedUidRanges.remove(ranges[i]);
5445 }
5446 }
5447
5448 try {
5449 mNetd.networkRejectNonSecureVpn(requireVpn, toUidRangeStableParcels(ranges));
5450 } catch (RemoteException | ServiceSpecificException e) {
5451 Log.e(TAG, "setRequireVpnForUids(" + requireVpn + ", "
5452 + Arrays.toString(ranges) + "): netd command failed: " + e);
5453 }
5454
5455 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
5456 final boolean curMetered = nai.networkCapabilities.isMetered();
5457 maybeNotifyNetworkBlocked(nai, curMetered, curMetered,
5458 mVpnBlockedUidRanges, newVpnBlockedUidRanges);
5459 }
5460
5461 mVpnBlockedUidRanges = newVpnBlockedUidRanges;
5462 }
5463
5464 @Override
5465 public void setLegacyLockdownVpnEnabled(boolean enabled) {
5466 enforceNetworkStackOrSettingsPermission();
5467 mHandler.post(() -> mLockdownEnabled = enabled);
5468 }
5469
5470 private boolean isLegacyLockdownNai(NetworkAgentInfo nai) {
5471 return mLockdownEnabled
5472 && getVpnType(nai) == VpnManager.TYPE_VPN_LEGACY
5473 && nai.networkCapabilities.appliesToUid(Process.FIRST_APPLICATION_UID);
5474 }
5475
5476 private NetworkAgentInfo getLegacyLockdownNai() {
5477 if (!mLockdownEnabled) {
5478 return null;
5479 }
5480 // The legacy lockdown VPN always only applies to userId 0.
5481 final NetworkAgentInfo nai = getVpnForUid(Process.FIRST_APPLICATION_UID);
5482 if (nai == null || !isLegacyLockdownNai(nai)) return null;
5483
5484 // The legacy lockdown VPN must always have exactly one underlying network.
5485 // This code may run on any thread and declaredUnderlyingNetworks may change, so store it in
5486 // a local variable. There is no need to make a copy because its contents cannot change.
5487 final Network[] underlying = nai.declaredUnderlyingNetworks;
5488 if (underlying == null || underlying.length != 1) {
5489 return null;
5490 }
5491
5492 // The legacy lockdown VPN always uses the default network.
5493 // If the VPN's underlying network is no longer the current default network, it means that
5494 // the default network has just switched, and the VPN is about to disconnect.
5495 // Report that the VPN is not connected, so the state of NetworkInfo objects overwritten
5496 // by filterForLegacyLockdown will be set to CONNECTING and not CONNECTED.
5497 final NetworkAgentInfo defaultNetwork = getDefaultNetwork();
5498 if (defaultNetwork == null || !defaultNetwork.network.equals(underlying[0])) {
5499 return null;
5500 }
5501
5502 return nai;
5503 };
5504
5505 // TODO: move all callers to filterForLegacyLockdown and delete this method.
5506 // This likely requires making sendLegacyNetworkBroadcast take a NetworkInfo object instead of
5507 // just a DetailedState object.
5508 private DetailedState getLegacyLockdownState(DetailedState origState) {
5509 if (origState != DetailedState.CONNECTED) {
5510 return origState;
5511 }
5512 return (mLockdownEnabled && getLegacyLockdownNai() == null)
5513 ? DetailedState.CONNECTING
5514 : DetailedState.CONNECTED;
5515 }
5516
5517 private void filterForLegacyLockdown(NetworkInfo ni) {
5518 if (!mLockdownEnabled || !ni.isConnected()) return;
5519 // The legacy lockdown VPN replaces the state of every network in CONNECTED state with the
5520 // state of its VPN. This is to ensure that when an underlying network connects, apps will
5521 // not see a CONNECTIVITY_ACTION broadcast for a network in state CONNECTED until the VPN
5522 // comes up, at which point there is a new CONNECTIVITY_ACTION broadcast for the underlying
5523 // network, this time with a state of CONNECTED.
5524 //
5525 // Now that the legacy lockdown code lives in ConnectivityService, and no longer has access
5526 // to the internal state of the Vpn object, always replace the state with CONNECTING. This
5527 // is not too far off the truth, since an always-on VPN, when not connected, is always
5528 // trying to reconnect.
5529 if (getLegacyLockdownNai() == null) {
5530 ni.setDetailedState(DetailedState.CONNECTING, "", null);
5531 }
5532 }
5533
5534 @Override
5535 public void setProvisioningNotificationVisible(boolean visible, int networkType,
5536 String action) {
5537 enforceSettingsPermission();
5538 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
5539 return;
5540 }
5541 final long ident = Binder.clearCallingIdentity();
5542 try {
5543 // Concatenate the range of types onto the range of NetIDs.
5544 int id = NetIdManager.MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
5545 mNotifier.setProvNotificationVisible(visible, id, action);
5546 } finally {
5547 Binder.restoreCallingIdentity(ident);
5548 }
5549 }
5550
5551 @Override
5552 public void setAirplaneMode(boolean enable) {
5553 enforceAirplaneModePermission();
5554 final long ident = Binder.clearCallingIdentity();
5555 try {
5556 final ContentResolver cr = mContext.getContentResolver();
5557 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
5558 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
5559 intent.putExtra("state", enable);
5560 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
5561 } finally {
5562 Binder.restoreCallingIdentity(ident);
5563 }
5564 }
5565
5566 private void onUserAdded(@NonNull final UserHandle user) {
5567 mPermissionMonitor.onUserAdded(user);
5568 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
5569 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
5570 }
5571 }
5572
5573 private void onUserRemoved(@NonNull final UserHandle user) {
5574 mPermissionMonitor.onUserRemoved(user);
5575 // If there was a network preference for this user, remove it.
5576 handleSetProfileNetworkPreference(new ProfileNetworkPreferences.Preference(user, null),
5577 null /* listener */);
5578 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
5579 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
5580 }
5581 }
5582
5583 private void onPackageChanged(@NonNull final String packageName) {
5584 // This is necessary in case a package is added or removed, but also when it's replaced to
5585 // run as a new UID by its manifest rules. Also, if a separate package shares the same UID
5586 // as one in the preferences, then it should follow the same routing as that other package,
5587 // which means updating the rules is never to be needed in this case (whether it joins or
5588 // leaves a UID with a preference).
5589 if (isMappedInOemNetworkPreference(packageName)) {
5590 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
5591 }
5592 }
5593
5594 private final BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
5595 @Override
5596 public void onReceive(Context context, Intent intent) {
5597 ensureRunningOnConnectivityServiceThread();
5598 final String action = intent.getAction();
5599 final UserHandle user = intent.getParcelableExtra(Intent.EXTRA_USER);
5600
5601 // User should be filled for below intents, check the existence.
5602 if (user == null) {
5603 Log.wtf(TAG, intent.getAction() + " broadcast without EXTRA_USER");
5604 return;
5605 }
5606
5607 if (Intent.ACTION_USER_ADDED.equals(action)) {
5608 onUserAdded(user);
5609 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
5610 onUserRemoved(user);
5611 } else {
5612 Log.wtf(TAG, "received unexpected intent: " + action);
5613 }
5614 }
5615 };
5616
5617 private final BroadcastReceiver mPackageIntentReceiver = new BroadcastReceiver() {
5618 @Override
5619 public void onReceive(Context context, Intent intent) {
5620 ensureRunningOnConnectivityServiceThread();
5621 switch (intent.getAction()) {
5622 case Intent.ACTION_PACKAGE_ADDED:
5623 case Intent.ACTION_PACKAGE_REMOVED:
5624 case Intent.ACTION_PACKAGE_REPLACED:
5625 onPackageChanged(intent.getData().getSchemeSpecificPart());
5626 break;
5627 default:
5628 Log.wtf(TAG, "received unexpected intent: " + intent.getAction());
5629 }
5630 }
5631 };
5632
5633 private final HashMap<Messenger, NetworkProviderInfo> mNetworkProviderInfos = new HashMap<>();
5634 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests = new HashMap<>();
5635
5636 private static class NetworkProviderInfo {
5637 public final String name;
5638 public final Messenger messenger;
5639 private final IBinder.DeathRecipient mDeathRecipient;
5640 public final int providerId;
5641
5642 NetworkProviderInfo(String name, Messenger messenger, int providerId,
5643 @NonNull IBinder.DeathRecipient deathRecipient) {
5644 this.name = name;
5645 this.messenger = messenger;
5646 this.providerId = providerId;
5647 mDeathRecipient = deathRecipient;
5648
5649 if (mDeathRecipient == null) {
5650 throw new AssertionError("Must pass a deathRecipient");
5651 }
5652 }
5653
5654 void connect(Context context, Handler handler) {
5655 try {
5656 messenger.getBinder().linkToDeath(mDeathRecipient, 0);
5657 } catch (RemoteException e) {
5658 mDeathRecipient.binderDied();
5659 }
5660 }
5661 }
5662
5663 private void ensureAllNetworkRequestsHaveType(List<NetworkRequest> requests) {
5664 for (int i = 0; i < requests.size(); i++) {
5665 ensureNetworkRequestHasType(requests.get(i));
5666 }
5667 }
5668
5669 private void ensureNetworkRequestHasType(NetworkRequest request) {
5670 if (request.type == NetworkRequest.Type.NONE) {
5671 throw new IllegalArgumentException(
5672 "All NetworkRequests in ConnectivityService must have a type");
5673 }
5674 }
5675
5676 /**
5677 * Tracks info about the requester.
5678 * Also used to notice when the calling process dies so as to self-expire
5679 */
5680 @VisibleForTesting
5681 protected class NetworkRequestInfo implements IBinder.DeathRecipient {
5682 // The requests to be satisfied in priority order. Non-multilayer requests will only have a
5683 // single NetworkRequest in mRequests.
5684 final List<NetworkRequest> mRequests;
5685
5686 // mSatisfier and mActiveRequest rely on one another therefore set them together.
5687 void setSatisfier(
5688 @Nullable final NetworkAgentInfo satisfier,
5689 @Nullable final NetworkRequest activeRequest) {
5690 mSatisfier = satisfier;
5691 mActiveRequest = activeRequest;
5692 }
5693
5694 // The network currently satisfying this NRI. Only one request in an NRI can have a
5695 // satisfier. For non-multilayer requests, only non-listen requests can have a satisfier.
5696 @Nullable
5697 private NetworkAgentInfo mSatisfier;
5698 NetworkAgentInfo getSatisfier() {
5699 return mSatisfier;
5700 }
5701
5702 // The request in mRequests assigned to a network agent. This is null if none of the
5703 // requests in mRequests can be satisfied. This member has the constraint of only being
5704 // accessible on the handler thread.
5705 @Nullable
5706 private NetworkRequest mActiveRequest;
5707 NetworkRequest getActiveRequest() {
5708 return mActiveRequest;
5709 }
5710
5711 final PendingIntent mPendingIntent;
5712 boolean mPendingIntentSent;
5713 @Nullable
5714 final Messenger mMessenger;
5715
5716 // Information about the caller that caused this object to be created.
5717 @Nullable
5718 private final IBinder mBinder;
5719 final int mPid;
5720 final int mUid;
5721 final @NetworkCallback.Flag int mCallbackFlags;
5722 @Nullable
5723 final String mCallingAttributionTag;
5724
5725 // Counter keeping track of this NRI.
5726 final PerUidCounter mPerUidCounter;
5727
5728 // Effective UID of this request. This is different from mUid when a privileged process
5729 // files a request on behalf of another UID. This UID is used to determine blocked status,
5730 // UID matching, and so on. mUid above is used for permission checks and to enforce the
5731 // maximum limit of registered callbacks per UID.
5732 final int mAsUid;
5733
paulhu48291862021-07-14 14:53:57 +08005734 // Preference order of this request.
5735 final int mPreferenceOrder;
paulhuc2198772021-05-26 15:19:20 +08005736
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00005737 // In order to preserve the mapping of NetworkRequest-to-callback when apps register
5738 // callbacks using a returned NetworkRequest, the original NetworkRequest needs to be
5739 // maintained for keying off of. This is only a concern when the original nri
5740 // mNetworkRequests changes which happens currently for apps that register callbacks to
5741 // track the default network. In those cases, the nri is updated to have mNetworkRequests
5742 // that match the per-app default nri that currently tracks the calling app's uid so that
5743 // callbacks are fired at the appropriate time. When the callbacks fire,
5744 // mNetworkRequestForCallback will be used so as to preserve the caller's mapping. When
5745 // callbacks are updated to key off of an nri vs NetworkRequest, this stops being an issue.
5746 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
5747 @NonNull
5748 private final NetworkRequest mNetworkRequestForCallback;
5749 NetworkRequest getNetworkRequestForCallback() {
5750 return mNetworkRequestForCallback;
5751 }
5752
5753 /**
5754 * Get the list of UIDs this nri applies to.
5755 */
5756 @NonNull
paulhu71ad4f12021-05-25 14:56:27 +08005757 Set<UidRange> getUids() {
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00005758 // networkCapabilities.getUids() returns a defensive copy.
5759 // multilayer requests will all have the same uids so return the first one.
5760 final Set<UidRange> uids = mRequests.get(0).networkCapabilities.getUidRanges();
5761 return (null == uids) ? new ArraySet<>() : uids;
5762 }
5763
5764 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r,
5765 @Nullable final PendingIntent pi, @Nullable String callingAttributionTag) {
paulhuc2198772021-05-26 15:19:20 +08005766 this(asUid, Collections.singletonList(r), r, pi, callingAttributionTag,
paulhu48291862021-07-14 14:53:57 +08005767 PREFERENCE_ORDER_INVALID);
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00005768 }
5769
5770 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
5771 @NonNull final NetworkRequest requestForCallback, @Nullable final PendingIntent pi,
paulhu48291862021-07-14 14:53:57 +08005772 @Nullable String callingAttributionTag, final int preferenceOrder) {
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00005773 ensureAllNetworkRequestsHaveType(r);
5774 mRequests = initializeRequests(r);
5775 mNetworkRequestForCallback = requestForCallback;
5776 mPendingIntent = pi;
5777 mMessenger = null;
5778 mBinder = null;
5779 mPid = getCallingPid();
5780 mUid = mDeps.getCallingUid();
5781 mAsUid = asUid;
5782 mPerUidCounter = getRequestCounter(this);
5783 mPerUidCounter.incrementCountOrThrow(mUid);
5784 /**
5785 * Location sensitive data not included in pending intent. Only included in
5786 * {@link NetworkCallback}.
5787 */
5788 mCallbackFlags = NetworkCallback.FLAG_NONE;
5789 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08005790 mPreferenceOrder = preferenceOrder;
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00005791 }
5792
5793 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r, @Nullable final Messenger m,
5794 @Nullable final IBinder binder,
5795 @NetworkCallback.Flag int callbackFlags,
5796 @Nullable String callingAttributionTag) {
5797 this(asUid, Collections.singletonList(r), r, m, binder, callbackFlags,
5798 callingAttributionTag);
5799 }
5800
5801 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
5802 @NonNull final NetworkRequest requestForCallback, @Nullable final Messenger m,
5803 @Nullable final IBinder binder,
5804 @NetworkCallback.Flag int callbackFlags,
5805 @Nullable String callingAttributionTag) {
5806 super();
5807 ensureAllNetworkRequestsHaveType(r);
5808 mRequests = initializeRequests(r);
5809 mNetworkRequestForCallback = requestForCallback;
5810 mMessenger = m;
5811 mBinder = binder;
5812 mPid = getCallingPid();
5813 mUid = mDeps.getCallingUid();
5814 mAsUid = asUid;
5815 mPendingIntent = null;
5816 mPerUidCounter = getRequestCounter(this);
5817 mPerUidCounter.incrementCountOrThrow(mUid);
5818 mCallbackFlags = callbackFlags;
5819 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08005820 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00005821 linkDeathRecipient();
5822 }
5823
5824 NetworkRequestInfo(@NonNull final NetworkRequestInfo nri,
5825 @NonNull final List<NetworkRequest> r) {
5826 super();
5827 ensureAllNetworkRequestsHaveType(r);
5828 mRequests = initializeRequests(r);
5829 mNetworkRequestForCallback = nri.getNetworkRequestForCallback();
5830 final NetworkAgentInfo satisfier = nri.getSatisfier();
5831 if (null != satisfier) {
5832 // If the old NRI was satisfied by an NAI, then it may have had an active request.
5833 // The active request is necessary to figure out what callbacks to send, in
5834 // particular then a network updates its capabilities.
5835 // As this code creates a new NRI with a new set of requests, figure out which of
5836 // the list of requests should be the active request. It is always the first
5837 // request of the list that can be satisfied by the satisfier since the order of
5838 // requests is a priority order.
5839 // Note even in the presence of a satisfier there may not be an active request,
5840 // when the satisfier is the no-service network.
5841 NetworkRequest activeRequest = null;
5842 for (final NetworkRequest candidate : r) {
5843 if (candidate.canBeSatisfiedBy(satisfier.networkCapabilities)) {
5844 activeRequest = candidate;
5845 break;
5846 }
5847 }
5848 setSatisfier(satisfier, activeRequest);
5849 }
5850 mMessenger = nri.mMessenger;
5851 mBinder = nri.mBinder;
5852 mPid = nri.mPid;
5853 mUid = nri.mUid;
5854 mAsUid = nri.mAsUid;
5855 mPendingIntent = nri.mPendingIntent;
5856 mPerUidCounter = getRequestCounter(this);
5857 mPerUidCounter.incrementCountOrThrow(mUid);
5858 mCallbackFlags = nri.mCallbackFlags;
5859 mCallingAttributionTag = nri.mCallingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08005860 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00005861 linkDeathRecipient();
5862 }
5863
5864 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r) {
paulhu48291862021-07-14 14:53:57 +08005865 this(asUid, Collections.singletonList(r), PREFERENCE_ORDER_INVALID);
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00005866 }
5867
paulhuc2198772021-05-26 15:19:20 +08005868 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
paulhu48291862021-07-14 14:53:57 +08005869 final int preferenceOrder) {
paulhuc2198772021-05-26 15:19:20 +08005870 this(asUid, r, r.get(0), null /* pi */, null /* callingAttributionTag */,
paulhu48291862021-07-14 14:53:57 +08005871 preferenceOrder);
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00005872 }
5873
5874 // True if this NRI is being satisfied. It also accounts for if the nri has its satisifer
5875 // set to the mNoServiceNetwork in which case mActiveRequest will be null thus returning
5876 // false.
5877 boolean isBeingSatisfied() {
5878 return (null != mSatisfier && null != mActiveRequest);
5879 }
5880
5881 boolean isMultilayerRequest() {
5882 return mRequests.size() > 1;
5883 }
5884
5885 private List<NetworkRequest> initializeRequests(List<NetworkRequest> r) {
5886 // Creating a defensive copy to prevent the sender from modifying the list being
5887 // reflected in the return value of this method.
5888 final List<NetworkRequest> tempRequests = new ArrayList<>(r);
5889 return Collections.unmodifiableList(tempRequests);
5890 }
5891
5892 void decrementRequestCount() {
5893 mPerUidCounter.decrementCount(mUid);
5894 }
5895
5896 void linkDeathRecipient() {
5897 if (null != mBinder) {
5898 try {
5899 mBinder.linkToDeath(this, 0);
5900 } catch (RemoteException e) {
5901 binderDied();
5902 }
5903 }
5904 }
5905
5906 void unlinkDeathRecipient() {
5907 if (null != mBinder) {
5908 mBinder.unlinkToDeath(this, 0);
5909 }
5910 }
5911
paulhu48291862021-07-14 14:53:57 +08005912 boolean hasHigherOrderThan(@NonNull final NetworkRequestInfo target) {
5913 // Compare two preference orders.
5914 return mPreferenceOrder < target.mPreferenceOrder;
paulhude5efb92021-05-26 21:56:03 +08005915 }
5916
paulhu48291862021-07-14 14:53:57 +08005917 int getPreferenceOrderForNetd() {
5918 if (mPreferenceOrder >= PREFERENCE_ORDER_NONE
5919 && mPreferenceOrder <= PREFERENCE_ORDER_LOWEST) {
5920 return mPreferenceOrder;
paulhude5efb92021-05-26 21:56:03 +08005921 }
paulhu48291862021-07-14 14:53:57 +08005922 return PREFERENCE_ORDER_NONE;
paulhude5efb92021-05-26 21:56:03 +08005923 }
5924
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00005925 @Override
5926 public void binderDied() {
5927 log("ConnectivityService NetworkRequestInfo binderDied(" +
James Mattis8f036802021-06-20 16:26:01 -07005928 "uid/pid:" + mUid + "/" + mPid + ", " + mBinder + ")");
Chalard Jean5bcc8382021-07-19 19:57:02 +09005929 // As an immutable collection, mRequests cannot change by the time the
5930 // lambda is evaluated on the handler thread so calling .get() from a binder thread
5931 // is acceptable. Use handleReleaseNetworkRequest and not directly
5932 // handleRemoveNetworkRequest so as to force a lookup in the requests map, in case
5933 // the app already unregistered the request.
5934 mHandler.post(() -> handleReleaseNetworkRequest(mRequests.get(0),
5935 mUid, false /* callOnUnavailable */));
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00005936 }
5937
5938 @Override
5939 public String toString() {
5940 final String asUidString = (mAsUid == mUid) ? "" : " asUid: " + mAsUid;
5941 return "uid/pid:" + mUid + "/" + mPid + asUidString + " activeRequest: "
5942 + (mActiveRequest == null ? null : mActiveRequest.requestId)
5943 + " callbackRequest: "
5944 + mNetworkRequestForCallback.requestId
5945 + " " + mRequests
5946 + (mPendingIntent == null ? "" : " to trigger " + mPendingIntent)
paulhude5efb92021-05-26 21:56:03 +08005947 + " callback flags: " + mCallbackFlags
paulhu48291862021-07-14 14:53:57 +08005948 + " order: " + mPreferenceOrder;
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00005949 }
5950 }
5951
5952 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
5953 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
5954 if (badCapability != null) {
5955 throw new IllegalArgumentException("Cannot request network with " + badCapability);
5956 }
5957 }
5958
5959 // This checks that the passed capabilities either do not request a
5960 // specific SSID/SignalStrength, or the calling app has permission to do so.
5961 private void ensureSufficientPermissionsForRequest(NetworkCapabilities nc,
5962 int callerPid, int callerUid, String callerPackageName) {
5963 if (null != nc.getSsid() && !checkSettingsPermission(callerPid, callerUid)) {
5964 throw new SecurityException("Insufficient permissions to request a specific SSID");
5965 }
5966
5967 if (nc.hasSignalStrength()
5968 && !checkNetworkSignalStrengthWakeupPermission(callerPid, callerUid)) {
5969 throw new SecurityException(
5970 "Insufficient permissions to request a specific signal strength");
5971 }
5972 mAppOpsManager.checkPackage(callerUid, callerPackageName);
5973
5974 if (!nc.getSubscriptionIds().isEmpty()) {
5975 enforceNetworkFactoryPermission();
5976 }
5977 }
5978
5979 private int[] getSignalStrengthThresholds(@NonNull final NetworkAgentInfo nai) {
5980 final SortedSet<Integer> thresholds = new TreeSet<>();
5981 synchronized (nai) {
5982 // mNetworkRequests may contain the same value multiple times in case of
5983 // multilayer requests. It won't matter in this case because the thresholds
5984 // will then be the same and be deduplicated as they enter the `thresholds` set.
5985 // TODO : have mNetworkRequests be a Set<NetworkRequestInfo> or the like.
5986 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
5987 for (final NetworkRequest req : nri.mRequests) {
5988 if (req.networkCapabilities.hasSignalStrength()
5989 && nai.satisfiesImmutableCapabilitiesOf(req)) {
5990 thresholds.add(req.networkCapabilities.getSignalStrength());
5991 }
5992 }
5993 }
5994 }
5995 return CollectionUtils.toIntArray(new ArrayList<>(thresholds));
5996 }
5997
5998 private void updateSignalStrengthThresholds(
5999 NetworkAgentInfo nai, String reason, NetworkRequest request) {
6000 final int[] thresholdsArray = getSignalStrengthThresholds(nai);
6001
6002 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
6003 String detail;
6004 if (request != null && request.networkCapabilities.hasSignalStrength()) {
6005 detail = reason + " " + request.networkCapabilities.getSignalStrength();
6006 } else {
6007 detail = reason;
6008 }
6009 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
6010 detail, Arrays.toString(thresholdsArray), nai.toShortString()));
6011 }
6012
6013 nai.onSignalStrengthThresholdsUpdated(thresholdsArray);
6014 }
6015
6016 private void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
6017 if (nc == null) {
6018 return;
6019 }
6020 NetworkSpecifier ns = nc.getNetworkSpecifier();
6021 if (ns == null) {
6022 return;
6023 }
6024 if (ns instanceof MatchAllNetworkSpecifier) {
6025 throw new IllegalArgumentException("A MatchAllNetworkSpecifier is not permitted");
6026 }
6027 }
6028
6029 private void ensureValid(NetworkCapabilities nc) {
6030 ensureValidNetworkSpecifier(nc);
6031 if (nc.isPrivateDnsBroken()) {
6032 throw new IllegalArgumentException("Can't request broken private DNS");
6033 }
6034 }
6035
6036 private boolean isTargetSdkAtleast(int version, int callingUid,
6037 @NonNull String callingPackageName) {
6038 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
6039 final PackageManager pm =
6040 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
6041 try {
6042 final int callingVersion = pm.getTargetSdkVersion(callingPackageName);
6043 if (callingVersion < version) return false;
6044 } catch (PackageManager.NameNotFoundException e) { }
6045 return true;
6046 }
6047
6048 @Override
6049 public NetworkRequest requestNetwork(int asUid, NetworkCapabilities networkCapabilities,
6050 int reqTypeInt, Messenger messenger, int timeoutMs, IBinder binder,
6051 int legacyType, int callbackFlags, @NonNull String callingPackageName,
6052 @Nullable String callingAttributionTag) {
6053 if (legacyType != TYPE_NONE && !checkNetworkStackPermission()) {
6054 if (isTargetSdkAtleast(Build.VERSION_CODES.M, mDeps.getCallingUid(),
6055 callingPackageName)) {
6056 throw new SecurityException("Insufficient permissions to specify legacy type");
6057 }
6058 }
6059 final NetworkCapabilities defaultNc = mDefaultRequest.mRequests.get(0).networkCapabilities;
6060 final int callingUid = mDeps.getCallingUid();
6061 // Privileged callers can track the default network of another UID by passing in a UID.
6062 if (asUid != Process.INVALID_UID) {
6063 enforceSettingsPermission();
6064 } else {
6065 asUid = callingUid;
6066 }
6067 final NetworkRequest.Type reqType;
6068 try {
6069 reqType = NetworkRequest.Type.values()[reqTypeInt];
6070 } catch (ArrayIndexOutOfBoundsException e) {
6071 throw new IllegalArgumentException("Unsupported request type " + reqTypeInt);
6072 }
6073 switch (reqType) {
6074 case TRACK_DEFAULT:
6075 // If the request type is TRACK_DEFAULT, the passed {@code networkCapabilities}
6076 // is unused and will be replaced by ones appropriate for the UID (usually, the
6077 // calling app). This allows callers to keep track of the default network.
6078 networkCapabilities = copyDefaultNetworkCapabilitiesForUid(
6079 defaultNc, asUid, callingUid, callingPackageName);
6080 enforceAccessPermission();
6081 break;
6082 case TRACK_SYSTEM_DEFAULT:
6083 enforceSettingsPermission();
6084 networkCapabilities = new NetworkCapabilities(defaultNc);
6085 break;
6086 case BACKGROUND_REQUEST:
6087 enforceNetworkStackOrSettingsPermission();
6088 // Fall-through since other checks are the same with normal requests.
6089 case REQUEST:
6090 networkCapabilities = new NetworkCapabilities(networkCapabilities);
6091 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
6092 callingAttributionTag);
6093 // TODO: this is incorrect. We mark the request as metered or not depending on
6094 // the state of the app when the request is filed, but we never change the
6095 // request if the app changes network state. http://b/29964605
6096 enforceMeteredApnPolicy(networkCapabilities);
6097 break;
6098 case LISTEN_FOR_BEST:
6099 enforceAccessPermission();
6100 networkCapabilities = new NetworkCapabilities(networkCapabilities);
6101 break;
6102 default:
6103 throw new IllegalArgumentException("Unsupported request type " + reqType);
6104 }
6105 ensureRequestableCapabilities(networkCapabilities);
6106 ensureSufficientPermissionsForRequest(networkCapabilities,
6107 Binder.getCallingPid(), callingUid, callingPackageName);
6108
6109 // Enforce FOREGROUND if the caller does not have permission to use background network.
6110 if (reqType == LISTEN_FOR_BEST) {
6111 restrictBackgroundRequestForCaller(networkCapabilities);
6112 }
6113
6114 // Set the UID range for this request to the single UID of the requester, unless the
6115 // requester has the permission to specify other UIDs.
6116 // This will overwrite any allowed UIDs in the requested capabilities. Though there
6117 // are no visible methods to set the UIDs, an app could use reflection to try and get
6118 // networks for other apps so it's essential that the UIDs are overwritten.
6119 // Also set the requester UID and package name in the request.
6120 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
6121 callingUid, callingPackageName);
6122
6123 if (timeoutMs < 0) {
6124 throw new IllegalArgumentException("Bad timeout specified");
6125 }
6126 ensureValid(networkCapabilities);
6127
6128 final NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
6129 nextNetworkRequestId(), reqType);
6130 final NetworkRequestInfo nri = getNriToRegister(
6131 asUid, networkRequest, messenger, binder, callbackFlags,
6132 callingAttributionTag);
6133 if (DBG) log("requestNetwork for " + nri);
6134
6135 // For TRACK_SYSTEM_DEFAULT callbacks, the capabilities have been modified since they were
6136 // copied from the default request above. (This is necessary to ensure, for example, that
6137 // the callback does not leak sensitive information to unprivileged apps.) Check that the
6138 // changes don't alter request matching.
6139 if (reqType == NetworkRequest.Type.TRACK_SYSTEM_DEFAULT &&
6140 (!networkCapabilities.equalRequestableCapabilities(defaultNc))) {
6141 throw new IllegalStateException(
6142 "TRACK_SYSTEM_DEFAULT capabilities don't match default request: "
6143 + networkCapabilities + " vs. " + defaultNc);
6144 }
6145
6146 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
6147 if (timeoutMs > 0) {
6148 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
6149 nri), timeoutMs);
6150 }
6151 return networkRequest;
6152 }
6153
6154 /**
6155 * Return the nri to be used when registering a network request. Specifically, this is used with
6156 * requests registered to track the default request. If there is currently a per-app default
6157 * tracking the app requestor, then we need to create a version of this nri that mirrors that of
6158 * the tracking per-app default so that callbacks are sent to the app requestor appropriately.
6159 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
6160 * when a privileged caller is tracking the default network for another uid.
6161 * @param nr the network request for the nri.
6162 * @param msgr the messenger for the nri.
6163 * @param binder the binder for the nri.
6164 * @param callingAttributionTag the calling attribution tag for the nri.
6165 * @return the nri to register.
6166 */
6167 private NetworkRequestInfo getNriToRegister(final int asUid, @NonNull final NetworkRequest nr,
6168 @Nullable final Messenger msgr, @Nullable final IBinder binder,
6169 @NetworkCallback.Flag int callbackFlags,
6170 @Nullable String callingAttributionTag) {
6171 final List<NetworkRequest> requests;
6172 if (NetworkRequest.Type.TRACK_DEFAULT == nr.type) {
6173 requests = copyDefaultNetworkRequestsForUid(
6174 asUid, nr.getRequestorUid(), nr.getRequestorPackageName());
6175 } else {
6176 requests = Collections.singletonList(nr);
6177 }
6178 return new NetworkRequestInfo(
6179 asUid, requests, nr, msgr, binder, callbackFlags, callingAttributionTag);
6180 }
6181
6182 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities,
6183 String callingPackageName, String callingAttributionTag) {
6184 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
6185 enforceConnectivityRestrictedNetworksPermission();
6186 } else {
6187 enforceChangePermission(callingPackageName, callingAttributionTag);
6188 }
6189 }
6190
6191 @Override
6192 public boolean requestBandwidthUpdate(Network network) {
6193 enforceAccessPermission();
6194 NetworkAgentInfo nai = null;
6195 if (network == null) {
6196 return false;
6197 }
6198 synchronized (mNetworkForNetId) {
6199 nai = mNetworkForNetId.get(network.getNetId());
6200 }
6201 if (nai != null) {
6202 nai.onBandwidthUpdateRequested();
6203 synchronized (mBandwidthRequests) {
6204 final int uid = mDeps.getCallingUid();
6205 Integer uidReqs = mBandwidthRequests.get(uid);
6206 if (uidReqs == null) {
6207 uidReqs = 0;
6208 }
6209 mBandwidthRequests.put(uid, ++uidReqs);
6210 }
6211 return true;
6212 }
6213 return false;
6214 }
6215
6216 private boolean isSystem(int uid) {
6217 return uid < Process.FIRST_APPLICATION_UID;
6218 }
6219
6220 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
6221 final int uid = mDeps.getCallingUid();
6222 if (isSystem(uid)) {
6223 // Exemption for system uid.
6224 return;
6225 }
6226 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
6227 // Policy already enforced.
6228 return;
6229 }
6230 final long ident = Binder.clearCallingIdentity();
6231 try {
6232 if (mPolicyManager.isUidRestrictedOnMeteredNetworks(uid)) {
6233 // If UID is restricted, don't allow them to bring up metered APNs.
6234 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
6235 }
6236 } finally {
6237 Binder.restoreCallingIdentity(ident);
6238 }
6239 }
6240
6241 @Override
6242 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
6243 PendingIntent operation, @NonNull String callingPackageName,
6244 @Nullable String callingAttributionTag) {
6245 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
6246 final int callingUid = mDeps.getCallingUid();
6247 networkCapabilities = new NetworkCapabilities(networkCapabilities);
6248 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
6249 callingAttributionTag);
6250 enforceMeteredApnPolicy(networkCapabilities);
6251 ensureRequestableCapabilities(networkCapabilities);
6252 ensureSufficientPermissionsForRequest(networkCapabilities,
6253 Binder.getCallingPid(), callingUid, callingPackageName);
6254 ensureValidNetworkSpecifier(networkCapabilities);
6255 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
6256 callingUid, callingPackageName);
6257
6258 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
6259 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
6260 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
6261 callingAttributionTag);
6262 if (DBG) log("pendingRequest for " + nri);
6263 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
6264 nri));
6265 return networkRequest;
6266 }
6267
6268 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
6269 mHandler.sendMessageDelayed(
6270 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
6271 mDeps.getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
6272 }
6273
6274 @Override
6275 public void releasePendingNetworkRequest(PendingIntent operation) {
6276 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
6277 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
6278 mDeps.getCallingUid(), 0, operation));
6279 }
6280
6281 // In order to implement the compatibility measure for pre-M apps that call
6282 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
6283 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
6284 // This ensures it has permission to do so.
6285 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
6286 if (nc == null) {
6287 return false;
6288 }
6289 int[] transportTypes = nc.getTransportTypes();
6290 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
6291 return false;
6292 }
6293 try {
6294 mContext.enforceCallingOrSelfPermission(
6295 android.Manifest.permission.ACCESS_WIFI_STATE,
6296 "ConnectivityService");
6297 } catch (SecurityException e) {
6298 return false;
6299 }
6300 return true;
6301 }
6302
6303 @Override
6304 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
6305 Messenger messenger, IBinder binder,
6306 @NetworkCallback.Flag int callbackFlags,
6307 @NonNull String callingPackageName, @NonNull String callingAttributionTag) {
6308 final int callingUid = mDeps.getCallingUid();
6309 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
6310 enforceAccessPermission();
6311 }
6312
6313 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
6314 ensureSufficientPermissionsForRequest(networkCapabilities,
6315 Binder.getCallingPid(), callingUid, callingPackageName);
6316 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
6317 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
6318 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
6319 // onLost and onAvailable callbacks when networks move in and out of the background.
6320 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
6321 // can't request networks.
6322 restrictBackgroundRequestForCaller(nc);
6323 ensureValid(nc);
6324
6325 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
6326 NetworkRequest.Type.LISTEN);
6327 NetworkRequestInfo nri =
6328 new NetworkRequestInfo(callingUid, networkRequest, messenger, binder, callbackFlags,
6329 callingAttributionTag);
6330 if (VDBG) log("listenForNetwork for " + nri);
6331
6332 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
6333 return networkRequest;
6334 }
6335
6336 @Override
6337 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
6338 PendingIntent operation, @NonNull String callingPackageName,
6339 @Nullable String callingAttributionTag) {
6340 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
6341 final int callingUid = mDeps.getCallingUid();
6342 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
6343 enforceAccessPermission();
6344 }
6345 ensureValid(networkCapabilities);
6346 ensureSufficientPermissionsForRequest(networkCapabilities,
6347 Binder.getCallingPid(), callingUid, callingPackageName);
6348 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
6349 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
6350
6351 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
6352 NetworkRequest.Type.LISTEN);
6353 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
6354 callingAttributionTag);
6355 if (VDBG) log("pendingListenForNetwork for " + nri);
6356
WeiZhang1cc3f172021-06-03 19:02:04 -05006357 mHandler.sendMessage(mHandler.obtainMessage(
6358 EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT, nri));
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00006359 }
6360
6361 /** Returns the next Network provider ID. */
6362 public final int nextNetworkProviderId() {
6363 return mNextNetworkProviderId.getAndIncrement();
6364 }
6365
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00006366 @Override
6367 public void releaseNetworkRequest(NetworkRequest networkRequest) {
6368 ensureNetworkRequestHasType(networkRequest);
6369 mHandler.sendMessage(mHandler.obtainMessage(
6370 EVENT_RELEASE_NETWORK_REQUEST, mDeps.getCallingUid(), 0, networkRequest));
6371 }
6372
6373 private void handleRegisterNetworkProvider(NetworkProviderInfo npi) {
6374 if (mNetworkProviderInfos.containsKey(npi.messenger)) {
6375 // Avoid creating duplicates. even if an app makes a direct AIDL call.
6376 // This will never happen if an app calls ConnectivityManager#registerNetworkProvider,
6377 // as that will throw if a duplicate provider is registered.
6378 loge("Attempt to register existing NetworkProviderInfo "
6379 + mNetworkProviderInfos.get(npi.messenger).name);
6380 return;
6381 }
6382
6383 if (DBG) log("Got NetworkProvider Messenger for " + npi.name);
6384 mNetworkProviderInfos.put(npi.messenger, npi);
6385 npi.connect(mContext, mTrackerHandler);
6386 }
6387
6388 @Override
6389 public int registerNetworkProvider(Messenger messenger, String name) {
6390 enforceNetworkFactoryOrSettingsPermission();
6391 Objects.requireNonNull(messenger, "messenger must be non-null");
6392 NetworkProviderInfo npi = new NetworkProviderInfo(name, messenger,
6393 nextNetworkProviderId(), () -> unregisterNetworkProvider(messenger));
6394 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_PROVIDER, npi));
6395 return npi.providerId;
6396 }
6397
6398 @Override
6399 public void unregisterNetworkProvider(Messenger messenger) {
6400 enforceNetworkFactoryOrSettingsPermission();
6401 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_PROVIDER, messenger));
6402 }
6403
6404 @Override
6405 public void offerNetwork(final int providerId,
6406 @NonNull final NetworkScore score, @NonNull final NetworkCapabilities caps,
6407 @NonNull final INetworkOfferCallback callback) {
6408 Objects.requireNonNull(score);
6409 Objects.requireNonNull(caps);
6410 Objects.requireNonNull(callback);
6411 final NetworkOffer offer = new NetworkOffer(
6412 FullScore.makeProspectiveScore(score, caps), caps, callback, providerId);
6413 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_OFFER, offer));
6414 }
6415
6416 @Override
6417 public void unofferNetwork(@NonNull final INetworkOfferCallback callback) {
6418 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_OFFER, callback));
6419 }
6420
6421 private void handleUnregisterNetworkProvider(Messenger messenger) {
6422 NetworkProviderInfo npi = mNetworkProviderInfos.remove(messenger);
6423 if (npi == null) {
6424 loge("Failed to find Messenger in unregisterNetworkProvider");
6425 return;
6426 }
6427 // Unregister all the offers from this provider
6428 final ArrayList<NetworkOfferInfo> toRemove = new ArrayList<>();
6429 for (final NetworkOfferInfo noi : mNetworkOffers) {
6430 if (noi.offer.providerId == npi.providerId) {
6431 // Can't call handleUnregisterNetworkOffer here because iteration is in progress
6432 toRemove.add(noi);
6433 }
6434 }
6435 for (final NetworkOfferInfo noi : toRemove) {
6436 handleUnregisterNetworkOffer(noi);
6437 }
6438 if (DBG) log("unregisterNetworkProvider for " + npi.name);
6439 }
6440
6441 @Override
6442 public void declareNetworkRequestUnfulfillable(@NonNull final NetworkRequest request) {
6443 if (request.hasTransport(TRANSPORT_TEST)) {
6444 enforceNetworkFactoryOrTestNetworksPermission();
6445 } else {
6446 enforceNetworkFactoryPermission();
6447 }
6448 final NetworkRequestInfo nri = mNetworkRequests.get(request);
6449 if (nri != null) {
6450 // declareNetworkRequestUnfulfillable() paths don't apply to multilayer requests.
6451 ensureNotMultilayerRequest(nri, "declareNetworkRequestUnfulfillable");
6452 mHandler.post(() -> handleReleaseNetworkRequest(
6453 nri.mRequests.get(0), mDeps.getCallingUid(), true));
6454 }
6455 }
6456
6457 // NOTE: Accessed on multiple threads, must be synchronized on itself.
6458 @GuardedBy("mNetworkForNetId")
6459 private final SparseArray<NetworkAgentInfo> mNetworkForNetId = new SparseArray<>();
6460 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
6461 // An entry is first reserved with NetIdManager, prior to being added to mNetworkForNetId, so
6462 // there may not be a strict 1:1 correlation between the two.
6463 private final NetIdManager mNetIdManager;
6464
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09006465 // Tracks all NetworkAgents that are currently registered.
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00006466 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
6467 private final ArraySet<NetworkAgentInfo> mNetworkAgentInfos = new ArraySet<>();
6468
6469 // UID ranges for users that are currently blocked by VPNs.
6470 // This array is accessed and iterated on multiple threads without holding locks, so its
6471 // contents must never be mutated. When the ranges change, the array is replaced with a new one
6472 // (on the handler thread).
6473 private volatile List<UidRange> mVpnBlockedUidRanges = new ArrayList<>();
6474
6475 // Must only be accessed on the handler thread
6476 @NonNull
6477 private final ArrayList<NetworkOfferInfo> mNetworkOffers = new ArrayList<>();
6478
6479 @GuardedBy("mBlockedAppUids")
6480 private final HashSet<Integer> mBlockedAppUids = new HashSet<>();
6481
6482 // Current OEM network preferences. This object must only be written to on the handler thread.
6483 // Since it is immutable and always non-null, other threads may read it if they only care
6484 // about seeing a consistent object but not that it is current.
6485 @NonNull
6486 private OemNetworkPreferences mOemNetworkPreferences =
6487 new OemNetworkPreferences.Builder().build();
6488 // Current per-profile network preferences. This object follows the same threading rules as
6489 // the OEM network preferences above.
6490 @NonNull
6491 private ProfileNetworkPreferences mProfileNetworkPreferences = new ProfileNetworkPreferences();
6492
paulhu71ad4f12021-05-25 14:56:27 +08006493 // A set of UIDs that should use mobile data preferentially if available. This object follows
6494 // the same threading rules as the OEM network preferences above.
6495 @NonNull
6496 private Set<Integer> mMobileDataPreferredUids = new ArraySet<>();
6497
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00006498 // OemNetworkPreferences activity String log entries.
6499 private static final int MAX_OEM_NETWORK_PREFERENCE_LOGS = 20;
6500 @NonNull
6501 private final LocalLog mOemNetworkPreferencesLogs =
6502 new LocalLog(MAX_OEM_NETWORK_PREFERENCE_LOGS);
6503
6504 /**
6505 * Determine whether a given package has a mapping in the current OemNetworkPreferences.
6506 * @param packageName the package name to check existence of a mapping for.
6507 * @return true if a mapping exists, false otherwise
6508 */
6509 private boolean isMappedInOemNetworkPreference(@NonNull final String packageName) {
6510 return mOemNetworkPreferences.getNetworkPreferences().containsKey(packageName);
6511 }
6512
6513 // The always-on request for an Internet-capable network that apps without a specific default
6514 // fall back to.
6515 @VisibleForTesting
6516 @NonNull
6517 final NetworkRequestInfo mDefaultRequest;
6518 // Collection of NetworkRequestInfo's used for default networks.
6519 @VisibleForTesting
6520 @NonNull
6521 final ArraySet<NetworkRequestInfo> mDefaultNetworkRequests = new ArraySet<>();
6522
6523 private boolean isPerAppDefaultRequest(@NonNull final NetworkRequestInfo nri) {
6524 return (mDefaultNetworkRequests.contains(nri) && mDefaultRequest != nri);
6525 }
6526
6527 /**
6528 * Return the default network request currently tracking the given uid.
6529 * @param uid the uid to check.
6530 * @return the NetworkRequestInfo tracking the given uid.
6531 */
6532 @NonNull
6533 private NetworkRequestInfo getDefaultRequestTrackingUid(final int uid) {
paulhude5efb92021-05-26 21:56:03 +08006534 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00006535 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00006536 // Checking the first request is sufficient as only multilayer requests will have more
6537 // than one request and for multilayer, all requests will track the same uids.
6538 if (nri.mRequests.get(0).networkCapabilities.appliesToUid(uid)) {
paulhude5efb92021-05-26 21:56:03 +08006539 // Find out the highest priority request.
paulhu48291862021-07-14 14:53:57 +08006540 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhude5efb92021-05-26 21:56:03 +08006541 highestPriorityNri = nri;
6542 }
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00006543 }
6544 }
paulhude5efb92021-05-26 21:56:03 +08006545 return highestPriorityNri;
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00006546 }
6547
6548 /**
6549 * Get a copy of the network requests of the default request that is currently tracking the
6550 * given uid.
6551 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
6552 * when a privileged caller is tracking the default network for another uid.
6553 * @param requestorUid the uid to check the default for.
6554 * @param requestorPackageName the requestor's package name.
6555 * @return a copy of the default's NetworkRequest that is tracking the given uid.
6556 */
6557 @NonNull
6558 private List<NetworkRequest> copyDefaultNetworkRequestsForUid(
6559 final int asUid, final int requestorUid, @NonNull final String requestorPackageName) {
6560 return copyNetworkRequestsForUid(
6561 getDefaultRequestTrackingUid(asUid).mRequests,
6562 asUid, requestorUid, requestorPackageName);
6563 }
6564
6565 /**
6566 * Copy the given nri's NetworkRequest collection.
6567 * @param requestsToCopy the NetworkRequest collection to be copied.
6568 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
6569 * when a privileged caller is tracking the default network for another uid.
6570 * @param requestorUid the uid to set on the copied collection.
6571 * @param requestorPackageName the package name to set on the copied collection.
6572 * @return the copied NetworkRequest collection.
6573 */
6574 @NonNull
6575 private List<NetworkRequest> copyNetworkRequestsForUid(
6576 @NonNull final List<NetworkRequest> requestsToCopy, final int asUid,
6577 final int requestorUid, @NonNull final String requestorPackageName) {
6578 final List<NetworkRequest> requests = new ArrayList<>();
6579 for (final NetworkRequest nr : requestsToCopy) {
6580 requests.add(new NetworkRequest(copyDefaultNetworkCapabilitiesForUid(
6581 nr.networkCapabilities, asUid, requestorUid, requestorPackageName),
6582 nr.legacyType, nextNetworkRequestId(), nr.type));
6583 }
6584 return requests;
6585 }
6586
6587 @NonNull
6588 private NetworkCapabilities copyDefaultNetworkCapabilitiesForUid(
6589 @NonNull final NetworkCapabilities netCapToCopy, final int asUid,
6590 final int requestorUid, @NonNull final String requestorPackageName) {
6591 // These capabilities are for a TRACK_DEFAULT callback, so:
6592 // 1. Remove NET_CAPABILITY_VPN, because it's (currently!) the only difference between
6593 // mDefaultRequest and a per-UID default request.
6594 // TODO: stop depending on the fact that these two unrelated things happen to be the same
6595 // 2. Always set the UIDs to asUid. restrictRequestUidsForCallerAndSetRequestorInfo will
6596 // not do this in the case of a privileged application.
6597 final NetworkCapabilities netCap = new NetworkCapabilities(netCapToCopy);
6598 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
6599 netCap.setSingleUid(asUid);
6600 restrictRequestUidsForCallerAndSetRequestorInfo(
6601 netCap, requestorUid, requestorPackageName);
6602 return netCap;
6603 }
6604
6605 /**
6606 * Get the nri that is currently being tracked for callbacks by per-app defaults.
6607 * @param nr the network request to check for equality against.
6608 * @return the nri if one exists, null otherwise.
6609 */
6610 @Nullable
6611 private NetworkRequestInfo getNriForAppRequest(@NonNull final NetworkRequest nr) {
6612 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
6613 if (nri.getNetworkRequestForCallback().equals(nr)) {
6614 return nri;
6615 }
6616 }
6617 return null;
6618 }
6619
6620 /**
6621 * Check if an nri is currently being managed by per-app default networking.
6622 * @param nri the nri to check.
6623 * @return true if this nri is currently being managed by per-app default networking.
6624 */
6625 private boolean isPerAppTrackedNri(@NonNull final NetworkRequestInfo nri) {
6626 // nri.mRequests.get(0) is only different from the original request filed in
6627 // nri.getNetworkRequestForCallback() if nri.mRequests was changed by per-app default
6628 // functionality therefore if these two don't match, it means this particular nri is
6629 // currently being managed by a per-app default.
6630 return nri.getNetworkRequestForCallback() != nri.mRequests.get(0);
6631 }
6632
6633 /**
6634 * Determine if an nri is a managed default request that disallows default networking.
6635 * @param nri the request to evaluate
6636 * @return true if device-default networking is disallowed
6637 */
6638 private boolean isDefaultBlocked(@NonNull final NetworkRequestInfo nri) {
6639 // Check if this nri is a managed default that supports the default network at its
6640 // lowest priority request.
6641 final NetworkRequest defaultNetworkRequest = mDefaultRequest.mRequests.get(0);
6642 final NetworkCapabilities lowestPriorityNetCap =
6643 nri.mRequests.get(nri.mRequests.size() - 1).networkCapabilities;
6644 return isPerAppDefaultRequest(nri)
6645 && !(defaultNetworkRequest.networkCapabilities.equalRequestableCapabilities(
6646 lowestPriorityNetCap));
6647 }
6648
6649 // Request used to optionally keep mobile data active even when higher
6650 // priority networks like Wi-Fi are active.
6651 private final NetworkRequest mDefaultMobileDataRequest;
6652
6653 // Request used to optionally keep wifi data active even when higher
6654 // priority networks like ethernet are active.
6655 private final NetworkRequest mDefaultWifiRequest;
6656
6657 // Request used to optionally keep vehicle internal network always active
6658 private final NetworkRequest mDefaultVehicleRequest;
6659
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00006660 // Sentinel NAI used to direct apps with default networks that should have no connectivity to a
6661 // network with no service. This NAI should never be matched against, nor should any public API
6662 // ever return the associated network. For this reason, this NAI is not in the list of available
6663 // NAIs. It is used in computeNetworkReassignment() to be set as the satisfier for non-device
6664 // default requests that don't support using the device default network which will ultimately
6665 // allow ConnectivityService to use this no-service network when calling makeDefaultForApps().
6666 @VisibleForTesting
6667 final NetworkAgentInfo mNoServiceNetwork;
6668
6669 // The NetworkAgentInfo currently satisfying the default request, if any.
6670 private NetworkAgentInfo getDefaultNetwork() {
6671 return mDefaultRequest.mSatisfier;
6672 }
6673
6674 private NetworkAgentInfo getDefaultNetworkForUid(final int uid) {
paulhude5efb92021-05-26 21:56:03 +08006675 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00006676 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
6677 // Currently, all network requests will have the same uids therefore checking the first
6678 // one is sufficient. If/when uids are tracked at the nri level, this can change.
6679 final Set<UidRange> uids = nri.mRequests.get(0).networkCapabilities.getUidRanges();
6680 if (null == uids) {
6681 continue;
6682 }
6683 for (final UidRange range : uids) {
6684 if (range.contains(uid)) {
paulhu48291862021-07-14 14:53:57 +08006685 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhude5efb92021-05-26 21:56:03 +08006686 highestPriorityNri = nri;
6687 }
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00006688 }
6689 }
6690 }
paulhude5efb92021-05-26 21:56:03 +08006691 return highestPriorityNri.getSatisfier();
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00006692 }
6693
6694 @Nullable
6695 private Network getNetwork(@Nullable NetworkAgentInfo nai) {
6696 return nai != null ? nai.network : null;
6697 }
6698
6699 private void ensureRunningOnConnectivityServiceThread() {
6700 if (mHandler.getLooper().getThread() != Thread.currentThread()) {
6701 throw new IllegalStateException(
6702 "Not running on ConnectivityService thread: "
6703 + Thread.currentThread().getName());
6704 }
6705 }
6706
6707 @VisibleForTesting
6708 protected boolean isDefaultNetwork(NetworkAgentInfo nai) {
6709 return nai == getDefaultNetwork();
6710 }
6711
6712 /**
6713 * Register a new agent with ConnectivityService to handle a network.
6714 *
6715 * @param na a reference for ConnectivityService to contact the agent asynchronously.
6716 * @param networkInfo the initial info associated with this network. It can be updated later :
6717 * see {@link #updateNetworkInfo}.
6718 * @param linkProperties the initial link properties of this network. They can be updated
6719 * later : see {@link #updateLinkProperties}.
6720 * @param networkCapabilities the initial capabilites of this network. They can be updated
6721 * later : see {@link #updateCapabilities}.
6722 * @param initialScore the initial score of the network. See
6723 * {@link NetworkAgentInfo#getCurrentScore}.
6724 * @param networkAgentConfig metadata about the network. This is never updated.
6725 * @param providerId the ID of the provider owning this NetworkAgent.
6726 * @return the network created for this agent.
6727 */
6728 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo networkInfo,
6729 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
6730 @NonNull NetworkScore initialScore, NetworkAgentConfig networkAgentConfig,
6731 int providerId) {
6732 Objects.requireNonNull(networkInfo, "networkInfo must not be null");
6733 Objects.requireNonNull(linkProperties, "linkProperties must not be null");
6734 Objects.requireNonNull(networkCapabilities, "networkCapabilities must not be null");
6735 Objects.requireNonNull(initialScore, "initialScore must not be null");
6736 Objects.requireNonNull(networkAgentConfig, "networkAgentConfig must not be null");
6737 if (networkCapabilities.hasTransport(TRANSPORT_TEST)) {
6738 enforceAnyPermissionOf(Manifest.permission.MANAGE_TEST_NETWORKS);
6739 } else {
6740 enforceNetworkFactoryPermission();
6741 }
6742
6743 final int uid = mDeps.getCallingUid();
6744 final long token = Binder.clearCallingIdentity();
6745 try {
6746 return registerNetworkAgentInternal(na, networkInfo, linkProperties,
6747 networkCapabilities, initialScore, networkAgentConfig, providerId, uid);
6748 } finally {
6749 Binder.restoreCallingIdentity(token);
6750 }
6751 }
6752
6753 private Network registerNetworkAgentInternal(INetworkAgent na, NetworkInfo networkInfo,
6754 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
6755 NetworkScore currentScore, NetworkAgentConfig networkAgentConfig, int providerId,
6756 int uid) {
6757 if (networkCapabilities.hasTransport(TRANSPORT_TEST)) {
6758 // Strictly, sanitizing here is unnecessary as the capabilities will be sanitized in
6759 // the call to mixInCapabilities below anyway, but sanitizing here means the NAI never
6760 // sees capabilities that may be malicious, which might prevent mistakes in the future.
6761 networkCapabilities = new NetworkCapabilities(networkCapabilities);
6762 networkCapabilities.restrictCapabilitesForTestNetwork(uid);
6763 }
6764
6765 LinkProperties lp = new LinkProperties(linkProperties);
6766
6767 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
6768 final NetworkAgentInfo nai = new NetworkAgentInfo(na,
6769 new Network(mNetIdManager.reserveNetId()), new NetworkInfo(networkInfo), lp, nc,
6770 currentScore, mContext, mTrackerHandler, new NetworkAgentConfig(networkAgentConfig),
6771 this, mNetd, mDnsResolver, providerId, uid, mLingerDelayMs,
6772 mQosCallbackTracker, mDeps);
6773
6774 // Make sure the LinkProperties and NetworkCapabilities reflect what the agent info says.
6775 processCapabilitiesFromAgent(nai, nc);
6776 nai.getAndSetNetworkCapabilities(mixInCapabilities(nai, nc));
6777 processLinkPropertiesFromAgent(nai, nai.linkProperties);
6778
6779 final String extraInfo = networkInfo.getExtraInfo();
6780 final String name = TextUtils.isEmpty(extraInfo)
6781 ? nai.networkCapabilities.getSsid() : extraInfo;
6782 if (DBG) log("registerNetworkAgent " + nai);
6783 mDeps.getNetworkStack().makeNetworkMonitor(
6784 nai.network, name, new NetworkMonitorCallbacks(nai));
6785 // NetworkAgentInfo registration will finish when the NetworkMonitor is created.
6786 // If the network disconnects or sends any other event before that, messages are deferred by
6787 // NetworkAgent until nai.connect(), which will be called when finalizing the
6788 // registration.
6789 return nai.network;
6790 }
6791
6792 private void handleRegisterNetworkAgent(NetworkAgentInfo nai, INetworkMonitor networkMonitor) {
6793 nai.onNetworkMonitorCreated(networkMonitor);
6794 if (VDBG) log("Got NetworkAgent Messenger");
6795 mNetworkAgentInfos.add(nai);
6796 synchronized (mNetworkForNetId) {
6797 mNetworkForNetId.put(nai.network.getNetId(), nai);
6798 }
6799
6800 try {
6801 networkMonitor.start();
6802 } catch (RemoteException e) {
6803 e.rethrowAsRuntimeException();
6804 }
6805 nai.notifyRegistered();
6806 NetworkInfo networkInfo = nai.networkInfo;
6807 updateNetworkInfo(nai, networkInfo);
6808 updateUids(nai, null, nai.networkCapabilities);
6809 }
6810
6811 private class NetworkOfferInfo implements IBinder.DeathRecipient {
6812 @NonNull public final NetworkOffer offer;
6813
6814 NetworkOfferInfo(@NonNull final NetworkOffer offer) {
6815 this.offer = offer;
6816 }
6817
6818 @Override
6819 public void binderDied() {
6820 mHandler.post(() -> handleUnregisterNetworkOffer(this));
6821 }
6822 }
6823
6824 private boolean isNetworkProviderWithIdRegistered(final int providerId) {
6825 for (final NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
6826 if (npi.providerId == providerId) return true;
6827 }
6828 return false;
6829 }
6830
6831 /**
6832 * Register or update a network offer.
6833 * @param newOffer The new offer. If the callback member is the same as an existing
6834 * offer, it is an update of that offer.
6835 */
6836 private void handleRegisterNetworkOffer(@NonNull final NetworkOffer newOffer) {
6837 ensureRunningOnConnectivityServiceThread();
6838 if (!isNetworkProviderWithIdRegistered(newOffer.providerId)) {
6839 // This may actually happen if a provider updates its score or registers and then
6840 // immediately unregisters. The offer would still be in the handler queue, but the
6841 // provider would have been removed.
6842 if (DBG) log("Received offer from an unregistered provider");
6843 return;
6844 }
6845 final NetworkOfferInfo existingOffer = findNetworkOfferInfoByCallback(newOffer.callback);
6846 if (null != existingOffer) {
6847 handleUnregisterNetworkOffer(existingOffer);
6848 newOffer.migrateFrom(existingOffer.offer);
6849 }
6850 final NetworkOfferInfo noi = new NetworkOfferInfo(newOffer);
6851 try {
6852 noi.offer.callback.asBinder().linkToDeath(noi, 0 /* flags */);
6853 } catch (RemoteException e) {
6854 noi.binderDied();
6855 return;
6856 }
6857 mNetworkOffers.add(noi);
6858 issueNetworkNeeds(noi);
6859 }
6860
6861 private void handleUnregisterNetworkOffer(@NonNull final NetworkOfferInfo noi) {
6862 ensureRunningOnConnectivityServiceThread();
6863 mNetworkOffers.remove(noi);
6864 noi.offer.callback.asBinder().unlinkToDeath(noi, 0 /* flags */);
6865 }
6866
6867 @Nullable private NetworkOfferInfo findNetworkOfferInfoByCallback(
6868 @NonNull final INetworkOfferCallback callback) {
6869 ensureRunningOnConnectivityServiceThread();
6870 for (final NetworkOfferInfo noi : mNetworkOffers) {
6871 if (noi.offer.callback.asBinder().equals(callback.asBinder())) return noi;
6872 }
6873 return null;
6874 }
6875
6876 /**
6877 * Called when receiving LinkProperties directly from a NetworkAgent.
6878 * Stores into |nai| any data coming from the agent that might also be written to the network's
6879 * LinkProperties by ConnectivityService itself. This ensures that the data provided by the
6880 * agent is not lost when updateLinkProperties is called.
6881 * This method should never alter the agent's LinkProperties, only store data in |nai|.
6882 */
6883 private void processLinkPropertiesFromAgent(NetworkAgentInfo nai, LinkProperties lp) {
6884 lp.ensureDirectlyConnectedRoutes();
6885 nai.clatd.setNat64PrefixFromRa(lp.getNat64Prefix());
6886 nai.networkAgentPortalData = lp.getCaptivePortalData();
6887 }
6888
6889 private void updateLinkProperties(NetworkAgentInfo networkAgent, @NonNull LinkProperties newLp,
6890 @NonNull LinkProperties oldLp) {
6891 int netId = networkAgent.network.getNetId();
6892
6893 // The NetworkAgent does not know whether clatd is running on its network or not, or whether
6894 // a NAT64 prefix was discovered by the DNS resolver. Before we do anything else, make sure
6895 // the LinkProperties for the network are accurate.
6896 networkAgent.clatd.fixupLinkProperties(oldLp, newLp);
6897
6898 updateInterfaces(newLp, oldLp, netId, networkAgent.networkCapabilities);
6899
6900 // update filtering rules, need to happen after the interface update so netd knows about the
6901 // new interface (the interface name -> index map becomes initialized)
6902 updateVpnFiltering(newLp, oldLp, networkAgent);
6903
6904 updateMtu(newLp, oldLp);
6905 // TODO - figure out what to do for clat
6906// for (LinkProperties lp : newLp.getStackedLinks()) {
6907// updateMtu(lp, null);
6908// }
6909 if (isDefaultNetwork(networkAgent)) {
6910 updateTcpBufferSizes(newLp.getTcpBufferSizes());
6911 }
6912
6913 updateRoutes(newLp, oldLp, netId);
6914 updateDnses(newLp, oldLp, netId);
6915 // Make sure LinkProperties represents the latest private DNS status.
6916 // This does not need to be done before updateDnses because the
6917 // LinkProperties are not the source of the private DNS configuration.
6918 // updateDnses will fetch the private DNS configuration from DnsManager.
6919 mDnsManager.updatePrivateDnsStatus(netId, newLp);
6920
6921 if (isDefaultNetwork(networkAgent)) {
6922 handleApplyDefaultProxy(newLp.getHttpProxy());
6923 } else {
6924 updateProxy(newLp, oldLp);
6925 }
6926
6927 updateWakeOnLan(newLp);
6928
6929 // Captive portal data is obtained from NetworkMonitor and stored in NetworkAgentInfo.
6930 // It is not always contained in the LinkProperties sent from NetworkAgents, and if it
6931 // does, it needs to be merged here.
6932 newLp.setCaptivePortalData(mergeCaptivePortalData(networkAgent.networkAgentPortalData,
6933 networkAgent.capportApiData));
6934
6935 // TODO - move this check to cover the whole function
6936 if (!Objects.equals(newLp, oldLp)) {
6937 synchronized (networkAgent) {
6938 networkAgent.linkProperties = newLp;
6939 }
6940 // Start or stop DNS64 detection and 464xlat according to network state.
6941 networkAgent.clatd.update();
6942 notifyIfacesChangedForNetworkStats();
6943 networkAgent.networkMonitor().notifyLinkPropertiesChanged(
6944 new LinkProperties(newLp, true /* parcelSensitiveFields */));
6945 if (networkAgent.everConnected) {
6946 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
6947 }
6948 }
6949
6950 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
6951 }
6952
6953 /**
6954 * @param naData captive portal data from NetworkAgent
6955 * @param apiData captive portal data from capport API
6956 */
6957 @Nullable
6958 private CaptivePortalData mergeCaptivePortalData(CaptivePortalData naData,
6959 CaptivePortalData apiData) {
6960 if (naData == null || apiData == null) {
6961 return naData == null ? apiData : naData;
6962 }
6963 final CaptivePortalData.Builder captivePortalBuilder =
6964 new CaptivePortalData.Builder(naData);
6965
6966 if (apiData.isCaptive()) {
6967 captivePortalBuilder.setCaptive(true);
6968 }
6969 if (apiData.isSessionExtendable()) {
6970 captivePortalBuilder.setSessionExtendable(true);
6971 }
6972 if (apiData.getExpiryTimeMillis() >= 0 || apiData.getByteLimit() >= 0) {
6973 // Expiry time, bytes remaining, refresh time all need to come from the same source,
6974 // otherwise data would be inconsistent. Prefer the capport API info if present,
6975 // as it can generally be refreshed more often.
6976 captivePortalBuilder.setExpiryTime(apiData.getExpiryTimeMillis());
6977 captivePortalBuilder.setBytesRemaining(apiData.getByteLimit());
6978 captivePortalBuilder.setRefreshTime(apiData.getRefreshTimeMillis());
6979 } else if (naData.getExpiryTimeMillis() < 0 && naData.getByteLimit() < 0) {
6980 // No source has time / bytes remaining information: surface the newest refresh time
6981 // for other fields
6982 captivePortalBuilder.setRefreshTime(
6983 Math.max(naData.getRefreshTimeMillis(), apiData.getRefreshTimeMillis()));
6984 }
6985
6986 // Prioritize the user portal URL from the network agent if the source is authenticated.
6987 if (apiData.getUserPortalUrl() != null && naData.getUserPortalUrlSource()
6988 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
6989 captivePortalBuilder.setUserPortalUrl(apiData.getUserPortalUrl(),
6990 apiData.getUserPortalUrlSource());
6991 }
6992 // Prioritize the venue information URL from the network agent if the source is
6993 // authenticated.
6994 if (apiData.getVenueInfoUrl() != null && naData.getVenueInfoUrlSource()
6995 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
6996 captivePortalBuilder.setVenueInfoUrl(apiData.getVenueInfoUrl(),
6997 apiData.getVenueInfoUrlSource());
6998 }
6999 return captivePortalBuilder.build();
7000 }
7001
7002 private void wakeupModifyInterface(String iface, NetworkCapabilities caps, boolean add) {
7003 // Marks are only available on WiFi interfaces. Checking for
7004 // marks on unsupported interfaces is harmless.
7005 if (!caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
7006 return;
7007 }
7008
7009 int mark = mResources.get().getInteger(R.integer.config_networkWakeupPacketMark);
7010 int mask = mResources.get().getInteger(R.integer.config_networkWakeupPacketMask);
7011
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00007012 // Mask/mark of zero will not detect anything interesting.
7013 // Don't install rules unless both values are nonzero.
7014 if (mark == 0 || mask == 0) {
7015 return;
7016 }
7017
7018 final String prefix = "iface:" + iface;
7019 try {
7020 if (add) {
7021 mNetd.wakeupAddInterface(iface, prefix, mark, mask);
7022 } else {
7023 mNetd.wakeupDelInterface(iface, prefix, mark, mask);
7024 }
7025 } catch (Exception e) {
7026 loge("Exception modifying wakeup packet monitoring: " + e);
7027 }
7028
7029 }
7030
7031 private void updateInterfaces(final @Nullable LinkProperties newLp,
7032 final @Nullable LinkProperties oldLp, final int netId,
7033 final @NonNull NetworkCapabilities caps) {
7034 final CompareResult<String> interfaceDiff = new CompareResult<>(
7035 oldLp != null ? oldLp.getAllInterfaceNames() : null,
7036 newLp != null ? newLp.getAllInterfaceNames() : null);
7037 if (!interfaceDiff.added.isEmpty()) {
7038 for (final String iface : interfaceDiff.added) {
7039 try {
7040 if (DBG) log("Adding iface " + iface + " to network " + netId);
7041 mNetd.networkAddInterface(netId, iface);
7042 wakeupModifyInterface(iface, caps, true);
7043 mDeps.reportNetworkInterfaceForTransports(mContext, iface,
7044 caps.getTransportTypes());
7045 } catch (Exception e) {
7046 logw("Exception adding interface: " + e);
7047 }
7048 }
7049 }
7050 for (final String iface : interfaceDiff.removed) {
7051 try {
7052 if (DBG) log("Removing iface " + iface + " from network " + netId);
7053 wakeupModifyInterface(iface, caps, false);
7054 mNetd.networkRemoveInterface(netId, iface);
7055 } catch (Exception e) {
7056 loge("Exception removing interface: " + e);
7057 }
7058 }
7059 }
7060
7061 // TODO: move to frameworks/libs/net.
7062 private RouteInfoParcel convertRouteInfo(RouteInfo route) {
7063 final String nextHop;
7064
7065 switch (route.getType()) {
7066 case RouteInfo.RTN_UNICAST:
7067 if (route.hasGateway()) {
7068 nextHop = route.getGateway().getHostAddress();
7069 } else {
7070 nextHop = INetd.NEXTHOP_NONE;
7071 }
7072 break;
7073 case RouteInfo.RTN_UNREACHABLE:
7074 nextHop = INetd.NEXTHOP_UNREACHABLE;
7075 break;
7076 case RouteInfo.RTN_THROW:
7077 nextHop = INetd.NEXTHOP_THROW;
7078 break;
7079 default:
7080 nextHop = INetd.NEXTHOP_NONE;
7081 break;
7082 }
7083
7084 final RouteInfoParcel rip = new RouteInfoParcel();
7085 rip.ifName = route.getInterface();
7086 rip.destination = route.getDestination().toString();
7087 rip.nextHop = nextHop;
7088 rip.mtu = route.getMtu();
7089
7090 return rip;
7091 }
7092
7093 /**
7094 * Have netd update routes from oldLp to newLp.
7095 * @return true if routes changed between oldLp and newLp
7096 */
7097 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
7098 // compare the route diff to determine which routes have been updated
7099 final CompareOrUpdateResult<RouteInfo.RouteKey, RouteInfo> routeDiff =
7100 new CompareOrUpdateResult<>(
7101 oldLp != null ? oldLp.getAllRoutes() : null,
7102 newLp != null ? newLp.getAllRoutes() : null,
7103 (r) -> r.getRouteKey());
7104
7105 // add routes before removing old in case it helps with continuous connectivity
7106
7107 // do this twice, adding non-next-hop routes first, then routes they are dependent on
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.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
7115 loge("Exception in networkAddRouteParcel for non-gateway: " + e);
7116 }
7117 }
7118 }
7119 for (RouteInfo route : routeDiff.added) {
7120 if (!route.hasGateway()) continue;
7121 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
7122 try {
7123 mNetd.networkAddRouteParcel(netId, convertRouteInfo(route));
7124 } catch (Exception e) {
7125 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
7126 loge("Exception in networkAddRouteParcel for gateway: " + e);
7127 }
7128 }
7129 }
7130
7131 for (RouteInfo route : routeDiff.removed) {
7132 if (VDBG || DDBG) log("Removing Route [" + route + "] from network " + netId);
7133 try {
7134 mNetd.networkRemoveRouteParcel(netId, convertRouteInfo(route));
7135 } catch (Exception e) {
7136 loge("Exception in networkRemoveRouteParcel: " + e);
7137 }
7138 }
7139
7140 for (RouteInfo route : routeDiff.updated) {
7141 if (VDBG || DDBG) log("Updating Route [" + route + "] from network " + netId);
7142 try {
7143 mNetd.networkUpdateRouteParcel(netId, convertRouteInfo(route));
7144 } catch (Exception e) {
7145 loge("Exception in networkUpdateRouteParcel: " + e);
7146 }
7147 }
7148 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty()
7149 || !routeDiff.updated.isEmpty();
7150 }
7151
7152 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
7153 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
7154 return; // no updating necessary
7155 }
7156
7157 if (DBG) {
7158 final Collection<InetAddress> dnses = newLp.getDnsServers();
7159 log("Setting DNS servers for network " + netId + " to " + dnses);
7160 }
7161 try {
7162 mDnsManager.noteDnsServersForNetwork(netId, newLp);
7163 mDnsManager.flushVmDnsCache();
7164 } catch (Exception e) {
7165 loge("Exception in setDnsConfigurationForNetwork: " + e);
7166 }
7167 }
7168
7169 private void updateVpnFiltering(LinkProperties newLp, LinkProperties oldLp,
7170 NetworkAgentInfo nai) {
7171 final String oldIface = oldLp != null ? oldLp.getInterfaceName() : null;
7172 final String newIface = newLp != null ? newLp.getInterfaceName() : null;
7173 final boolean wasFiltering = requiresVpnIsolation(nai, nai.networkCapabilities, oldLp);
7174 final boolean needsFiltering = requiresVpnIsolation(nai, nai.networkCapabilities, newLp);
7175
7176 if (!wasFiltering && !needsFiltering) {
7177 // Nothing to do.
7178 return;
7179 }
7180
7181 if (Objects.equals(oldIface, newIface) && (wasFiltering == needsFiltering)) {
7182 // Nothing changed.
7183 return;
7184 }
7185
7186 final Set<UidRange> ranges = nai.networkCapabilities.getUidRanges();
7187 final int vpnAppUid = nai.networkCapabilities.getOwnerUid();
7188 // TODO: this create a window of opportunity for apps to receive traffic between the time
7189 // when the old rules are removed and the time when new rules are added. To fix this,
7190 // make eBPF support two allowlisted interfaces so here new rules can be added before the
7191 // old rules are being removed.
7192 if (wasFiltering) {
7193 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, ranges, vpnAppUid);
7194 }
7195 if (needsFiltering) {
7196 mPermissionMonitor.onVpnUidRangesAdded(newIface, ranges, vpnAppUid);
7197 }
7198 }
7199
7200 private void updateWakeOnLan(@NonNull LinkProperties lp) {
7201 if (mWolSupportedInterfaces == null) {
7202 mWolSupportedInterfaces = new ArraySet<>(mResources.get().getStringArray(
7203 R.array.config_wakeonlan_supported_interfaces));
7204 }
7205 lp.setWakeOnLanSupported(mWolSupportedInterfaces.contains(lp.getInterfaceName()));
7206 }
7207
7208 private int getNetworkPermission(NetworkCapabilities nc) {
7209 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
7210 return INetd.PERMISSION_SYSTEM;
7211 }
7212 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
7213 return INetd.PERMISSION_NETWORK;
7214 }
7215 return INetd.PERMISSION_NONE;
7216 }
7217
7218 private void updateNetworkPermissions(@NonNull final NetworkAgentInfo nai,
7219 @NonNull final NetworkCapabilities newNc) {
7220 final int oldPermission = getNetworkPermission(nai.networkCapabilities);
7221 final int newPermission = getNetworkPermission(newNc);
7222 if (oldPermission != newPermission && nai.created && !nai.isVPN()) {
7223 try {
7224 mNetd.networkSetPermissionForNetwork(nai.network.getNetId(), newPermission);
7225 } catch (RemoteException | ServiceSpecificException e) {
7226 loge("Exception in networkSetPermissionForNetwork: " + e);
7227 }
7228 }
7229 }
7230
7231 /**
7232 * Called when receiving NetworkCapabilities directly from a NetworkAgent.
7233 * Stores into |nai| any data coming from the agent that might also be written to the network's
7234 * NetworkCapabilities by ConnectivityService itself. This ensures that the data provided by the
7235 * agent is not lost when updateCapabilities is called.
7236 * This method should never alter the agent's NetworkCapabilities, only store data in |nai|.
7237 */
7238 private void processCapabilitiesFromAgent(NetworkAgentInfo nai, NetworkCapabilities nc) {
7239 // Note: resetting the owner UID before storing the agent capabilities in NAI means that if
7240 // the agent attempts to change the owner UID, then nai.declaredCapabilities will not
7241 // actually be the same as the capabilities sent by the agent. Still, it is safer to reset
7242 // the owner UID here and behave as if the agent had never tried to change it.
7243 if (nai.networkCapabilities.getOwnerUid() != nc.getOwnerUid()) {
7244 Log.e(TAG, nai.toShortString() + ": ignoring attempt to change owner from "
7245 + nai.networkCapabilities.getOwnerUid() + " to " + nc.getOwnerUid());
7246 nc.setOwnerUid(nai.networkCapabilities.getOwnerUid());
7247 }
7248 nai.declaredCapabilities = new NetworkCapabilities(nc);
7249 }
7250
7251 /** Modifies |newNc| based on the capabilities of |underlyingNetworks| and |agentCaps|. */
7252 @VisibleForTesting
7253 void applyUnderlyingCapabilities(@Nullable Network[] underlyingNetworks,
7254 @NonNull NetworkCapabilities agentCaps, @NonNull NetworkCapabilities newNc) {
7255 underlyingNetworks = underlyingNetworksOrDefault(
7256 agentCaps.getOwnerUid(), underlyingNetworks);
7257 long transportTypes = NetworkCapabilitiesUtils.packBits(agentCaps.getTransportTypes());
7258 int downKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
7259 int upKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
7260 // metered if any underlying is metered, or originally declared metered by the agent.
7261 boolean metered = !agentCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
7262 boolean roaming = false; // roaming if any underlying is roaming
7263 boolean congested = false; // congested if any underlying is congested
7264 boolean suspended = true; // suspended if all underlying are suspended
7265
7266 boolean hadUnderlyingNetworks = false;
7267 if (null != underlyingNetworks) {
7268 for (Network underlyingNetwork : underlyingNetworks) {
7269 final NetworkAgentInfo underlying =
7270 getNetworkAgentInfoForNetwork(underlyingNetwork);
7271 if (underlying == null) continue;
7272
7273 final NetworkCapabilities underlyingCaps = underlying.networkCapabilities;
7274 hadUnderlyingNetworks = true;
7275 for (int underlyingType : underlyingCaps.getTransportTypes()) {
7276 transportTypes |= 1L << underlyingType;
7277 }
7278
7279 // Merge capabilities of this underlying network. For bandwidth, assume the
7280 // worst case.
7281 downKbps = NetworkCapabilities.minBandwidth(downKbps,
7282 underlyingCaps.getLinkDownstreamBandwidthKbps());
7283 upKbps = NetworkCapabilities.minBandwidth(upKbps,
7284 underlyingCaps.getLinkUpstreamBandwidthKbps());
7285 // If this underlying network is metered, the VPN is metered (it may cost money
7286 // to send packets on this network).
7287 metered |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
7288 // If this underlying network is roaming, the VPN is roaming (the billing structure
7289 // is different than the usual, local one).
7290 roaming |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_ROAMING);
7291 // If this underlying network is congested, the VPN is congested (the current
7292 // condition of the network affects the performance of this network).
7293 congested |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_CONGESTED);
7294 // If this network is not suspended, the VPN is not suspended (the VPN
7295 // is able to transfer some data).
7296 suspended &= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
7297 }
7298 }
7299 if (!hadUnderlyingNetworks) {
7300 // No idea what the underlying networks are; assume reasonable defaults
7301 metered = true;
7302 roaming = false;
7303 congested = false;
7304 suspended = false;
7305 }
7306
7307 newNc.setTransportTypes(NetworkCapabilitiesUtils.unpackBits(transportTypes));
7308 newNc.setLinkDownstreamBandwidthKbps(downKbps);
7309 newNc.setLinkUpstreamBandwidthKbps(upKbps);
7310 newNc.setCapability(NET_CAPABILITY_NOT_METERED, !metered);
7311 newNc.setCapability(NET_CAPABILITY_NOT_ROAMING, !roaming);
7312 newNc.setCapability(NET_CAPABILITY_NOT_CONGESTED, !congested);
7313 newNc.setCapability(NET_CAPABILITY_NOT_SUSPENDED, !suspended);
7314 }
7315
7316 /**
7317 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
7318 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
7319 * and foreground status).
7320 */
7321 @NonNull
7322 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
7323 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
7324 // Don't complain for VPNs since they're not driven by requests and there is no risk of
7325 // causing a connect/teardown loop.
7326 // TODO: remove this altogether and make it the responsibility of the NetworkProviders to
7327 // avoid connect/teardown loops.
7328 if (nai.everConnected &&
7329 !nai.isVPN() &&
7330 !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
7331 // TODO: consider not complaining when a network agent degrades its capabilities if this
7332 // does not cause any request (that is not a listen) currently matching that agent to
7333 // stop being matched by the updated agent.
7334 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
7335 if (!TextUtils.isEmpty(diff)) {
7336 Log.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
7337 }
7338 }
7339
7340 // Don't modify caller's NetworkCapabilities.
7341 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
7342 if (nai.lastValidated) {
7343 newNc.addCapability(NET_CAPABILITY_VALIDATED);
7344 } else {
7345 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
7346 }
7347 if (nai.lastCaptivePortalDetected) {
7348 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
7349 } else {
7350 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
7351 }
7352 if (nai.isBackgroundNetwork()) {
7353 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
7354 } else {
7355 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
7356 }
7357 if (nai.partialConnectivity) {
7358 newNc.addCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
7359 } else {
7360 newNc.removeCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
7361 }
7362 newNc.setPrivateDnsBroken(nai.networkCapabilities.isPrivateDnsBroken());
7363
7364 // TODO : remove this once all factories are updated to send NOT_SUSPENDED and NOT_ROAMING
7365 if (!newNc.hasTransport(TRANSPORT_CELLULAR)) {
7366 newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
7367 newNc.addCapability(NET_CAPABILITY_NOT_ROAMING);
7368 }
7369
Lorenzo Colittibd079452021-07-02 11:47:57 +09007370 if (nai.propagateUnderlyingCapabilities()) {
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00007371 applyUnderlyingCapabilities(nai.declaredUnderlyingNetworks, nai.declaredCapabilities,
7372 newNc);
7373 }
7374
7375 return newNc;
7376 }
7377
7378 private void updateNetworkInfoForRoamingAndSuspended(NetworkAgentInfo nai,
7379 NetworkCapabilities prevNc, NetworkCapabilities newNc) {
7380 final boolean prevSuspended = !prevNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
7381 final boolean suspended = !newNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
7382 final boolean prevRoaming = !prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
7383 final boolean roaming = !newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
7384 if (prevSuspended != suspended) {
7385 // TODO (b/73132094) : remove this call once the few users of onSuspended and
7386 // onResumed have been removed.
7387 notifyNetworkCallbacks(nai, suspended ? ConnectivityManager.CALLBACK_SUSPENDED
7388 : ConnectivityManager.CALLBACK_RESUMED);
7389 }
7390 if (prevSuspended != suspended || prevRoaming != roaming) {
7391 // updateNetworkInfo will mix in the suspended info from the capabilities and
7392 // take appropriate action for the network having possibly changed state.
7393 updateNetworkInfo(nai, nai.networkInfo);
7394 }
7395 }
7396
7397 /**
7398 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
7399 *
7400 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
7401 * capabilities we manage and store in {@code nai}, such as validated status and captive
7402 * portal status)
7403 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
7404 * potentially triggers rematches.
7405 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
7406 * change.)
7407 *
7408 * @param oldScore score of the network before any of the changes that prompted us
7409 * to call this function.
7410 * @param nai the network having its capabilities updated.
7411 * @param nc the new network capabilities.
7412 */
7413 private void updateCapabilities(final int oldScore, @NonNull final NetworkAgentInfo nai,
7414 @NonNull final NetworkCapabilities nc) {
7415 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
7416 if (Objects.equals(nai.networkCapabilities, newNc)) return;
7417 updateNetworkPermissions(nai, newNc);
7418 final NetworkCapabilities prevNc = nai.getAndSetNetworkCapabilities(newNc);
7419
7420 updateUids(nai, prevNc, newNc);
7421 nai.updateScoreForNetworkAgentUpdate();
7422
7423 if (nai.getCurrentScore() == oldScore && newNc.equalRequestableCapabilities(prevNc)) {
7424 // If the requestable capabilities haven't changed, and the score hasn't changed, then
7425 // the change we're processing can't affect any requests, it can only affect the listens
7426 // on this network. We might have been called by rematchNetworkAndRequests when a
7427 // network changed foreground state.
7428 processListenRequests(nai);
7429 } else {
7430 // If the requestable capabilities have changed or the score changed, we can't have been
7431 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
7432 rematchAllNetworksAndRequests();
7433 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
7434 }
7435 updateNetworkInfoForRoamingAndSuspended(nai, prevNc, newNc);
7436
7437 final boolean oldMetered = prevNc.isMetered();
7438 final boolean newMetered = newNc.isMetered();
7439 final boolean meteredChanged = oldMetered != newMetered;
7440
7441 if (meteredChanged) {
7442 maybeNotifyNetworkBlocked(nai, oldMetered, newMetered,
7443 mVpnBlockedUidRanges, mVpnBlockedUidRanges);
7444 }
7445
7446 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING)
7447 != newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
7448
7449 // Report changes that are interesting for network statistics tracking.
7450 if (meteredChanged || roamingChanged) {
7451 notifyIfacesChangedForNetworkStats();
7452 }
7453
7454 // This network might have been underlying another network. Propagate its capabilities.
7455 propagateUnderlyingNetworkCapabilities(nai.network);
7456
7457 if (!newNc.equalsTransportTypes(prevNc)) {
7458 mDnsManager.updateTransportsForNetwork(
7459 nai.network.getNetId(), newNc.getTransportTypes());
7460 }
lucaslin53e8a262021-06-08 01:43:59 +08007461
7462 maybeSendProxyBroadcast(nai, prevNc, newNc);
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00007463 }
7464
7465 /** Convenience method to update the capabilities for a given network. */
7466 private void updateCapabilitiesForNetwork(NetworkAgentInfo nai) {
7467 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
7468 }
7469
7470 /**
7471 * Returns whether VPN isolation (ingress interface filtering) should be applied on the given
7472 * network.
7473 *
7474 * Ingress interface filtering enforces that all apps under the given network can only receive
7475 * packets from the network's interface (and loopback). This is important for VPNs because
7476 * apps that cannot bypass a fully-routed VPN shouldn't be able to receive packets from any
7477 * non-VPN interfaces.
7478 *
7479 * As a result, this method should return true iff
7480 * 1. the network is an app VPN (not legacy VPN)
7481 * 2. the VPN does not allow bypass
7482 * 3. the VPN is fully-routed
7483 * 4. the VPN interface is non-null
7484 *
7485 * @see INetd#firewallAddUidInterfaceRules
7486 * @see INetd#firewallRemoveUidInterfaceRules
7487 */
7488 private boolean requiresVpnIsolation(@NonNull NetworkAgentInfo nai, NetworkCapabilities nc,
7489 LinkProperties lp) {
7490 if (nc == null || lp == null) return false;
7491 return nai.isVPN()
7492 && !nai.networkAgentConfig.allowBypass
7493 && nc.getOwnerUid() != Process.SYSTEM_UID
7494 && lp.getInterfaceName() != null
7495 && (lp.hasIpv4DefaultRoute() || lp.hasIpv4UnreachableDefaultRoute())
7496 && (lp.hasIpv6DefaultRoute() || lp.hasIpv6UnreachableDefaultRoute());
7497 }
7498
7499 private static UidRangeParcel[] toUidRangeStableParcels(final @NonNull Set<UidRange> ranges) {
7500 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.size()];
7501 int index = 0;
7502 for (UidRange range : ranges) {
7503 stableRanges[index] = new UidRangeParcel(range.start, range.stop);
7504 index++;
7505 }
7506 return stableRanges;
7507 }
7508
7509 private static UidRangeParcel[] toUidRangeStableParcels(UidRange[] ranges) {
7510 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.length];
7511 for (int i = 0; i < ranges.length; i++) {
7512 stableRanges[i] = new UidRangeParcel(ranges[i].start, ranges[i].stop);
7513 }
7514 return stableRanges;
7515 }
7516
7517 private void maybeCloseSockets(NetworkAgentInfo nai, UidRangeParcel[] ranges,
7518 int[] exemptUids) {
7519 if (nai.isVPN() && !nai.networkAgentConfig.allowBypass) {
7520 try {
7521 mNetd.socketDestroy(ranges, exemptUids);
7522 } catch (Exception e) {
7523 loge("Exception in socket destroy: ", e);
7524 }
7525 }
7526 }
7527
paulhude5efb92021-05-26 21:56:03 +08007528 private void updateVpnUidRanges(boolean add, NetworkAgentInfo nai, Set<UidRange> uidRanges) {
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00007529 int[] exemptUids = new int[2];
7530 // TODO: Excluding VPN_UID is necessary in order to not to kill the TCP connection used
7531 // by PPTP. Fix this by making Vpn set the owner UID to VPN_UID instead of system when
7532 // starting a legacy VPN, and remove VPN_UID here. (b/176542831)
7533 exemptUids[0] = VPN_UID;
7534 exemptUids[1] = nai.networkCapabilities.getOwnerUid();
7535 UidRangeParcel[] ranges = toUidRangeStableParcels(uidRanges);
7536
7537 maybeCloseSockets(nai, ranges, exemptUids);
7538 try {
7539 if (add) {
paulhude2a2392021-06-09 16:11:35 +08007540 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08007541 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00007542 } else {
paulhude2a2392021-06-09 16:11:35 +08007543 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08007544 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00007545 }
7546 } catch (Exception e) {
7547 loge("Exception while " + (add ? "adding" : "removing") + " uid ranges " + uidRanges +
7548 " on netId " + nai.network.netId + ". " + e);
7549 }
7550 maybeCloseSockets(nai, ranges, exemptUids);
7551 }
7552
lucaslin53e8a262021-06-08 01:43:59 +08007553 private boolean isProxySetOnAnyDefaultNetwork() {
7554 ensureRunningOnConnectivityServiceThread();
7555 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
7556 final NetworkAgentInfo nai = nri.getSatisfier();
7557 if (nai != null && nai.linkProperties.getHttpProxy() != null) {
7558 return true;
7559 }
7560 }
7561 return false;
7562 }
7563
7564 private void maybeSendProxyBroadcast(NetworkAgentInfo nai, NetworkCapabilities prevNc,
7565 NetworkCapabilities newNc) {
7566 // When the apps moved from/to a VPN, a proxy broadcast is needed to inform the apps that
7567 // the proxy might be changed since the default network satisfied by the apps might also
7568 // changed.
7569 // TODO: Try to track the default network that apps use and only send a proxy broadcast when
7570 // that happens to prevent false alarms.
7571 if (nai.isVPN() && nai.everConnected && !NetworkCapabilities.hasSameUids(prevNc, newNc)
7572 && (nai.linkProperties.getHttpProxy() != null || isProxySetOnAnyDefaultNetwork())) {
7573 mProxyTracker.sendProxyBroadcast();
7574 }
7575 }
7576
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00007577 private void updateUids(NetworkAgentInfo nai, NetworkCapabilities prevNc,
7578 NetworkCapabilities newNc) {
7579 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUidRanges();
7580 Set<UidRange> newRanges = null == newNc ? null : newNc.getUidRanges();
7581 if (null == prevRanges) prevRanges = new ArraySet<>();
7582 if (null == newRanges) newRanges = new ArraySet<>();
7583 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
7584
7585 prevRanges.removeAll(newRanges);
7586 newRanges.removeAll(prevRangesCopy);
7587
7588 try {
7589 // When updating the VPN uid routing rules, add the new range first then remove the old
7590 // range. If old range were removed first, there would be a window between the old
7591 // range being removed and the new range being added, during which UIDs contained
7592 // in both ranges are not subject to any VPN routing rules. Adding new range before
7593 // removing old range works because, unlike the filtering rules below, it's possible to
7594 // add duplicate UID routing rules.
7595 // TODO: calculate the intersection of add & remove. Imagining that we are trying to
7596 // remove uid 3 from a set containing 1-5. Intersection of the prev and new sets is:
7597 // [1-5] & [1-2],[4-5] == [3]
7598 // Then we can do:
7599 // maybeCloseSockets([3])
7600 // mNetd.networkAddUidRanges([1-2],[4-5])
7601 // mNetd.networkRemoveUidRanges([1-5])
7602 // maybeCloseSockets([3])
7603 // This can prevent the sockets of uid 1-2, 4-5 from being closed. It also reduce the
7604 // number of binder calls from 6 to 4.
7605 if (!newRanges.isEmpty()) {
paulhude5efb92021-05-26 21:56:03 +08007606 updateVpnUidRanges(true, nai, newRanges);
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00007607 }
7608 if (!prevRanges.isEmpty()) {
paulhude5efb92021-05-26 21:56:03 +08007609 updateVpnUidRanges(false, nai, prevRanges);
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00007610 }
7611 final boolean wasFiltering = requiresVpnIsolation(nai, prevNc, nai.linkProperties);
7612 final boolean shouldFilter = requiresVpnIsolation(nai, newNc, nai.linkProperties);
7613 final String iface = nai.linkProperties.getInterfaceName();
7614 // For VPN uid interface filtering, old ranges need to be removed before new ranges can
7615 // be added, due to the range being expanded and stored as individual UIDs. For example
7616 // the UIDs might be updated from [0, 99999] to ([0, 10012], [10014, 99999]) which means
7617 // prevRanges = [0, 99999] while newRanges = [0, 10012], [10014, 99999]. If prevRanges
7618 // were added first and then newRanges got removed later, there would be only one uid
7619 // 10013 left. A consequence of removing old ranges before adding new ranges is that
7620 // there is now a window of opportunity when the UIDs are not subject to any filtering.
7621 // Note that this is in contrast with the (more robust) update of VPN routing rules
7622 // above, where the addition of new ranges happens before the removal of old ranges.
7623 // TODO Fix this window by computing an accurate diff on Set<UidRange>, so the old range
7624 // to be removed will never overlap with the new range to be added.
7625 if (wasFiltering && !prevRanges.isEmpty()) {
7626 mPermissionMonitor.onVpnUidRangesRemoved(iface, prevRanges, prevNc.getOwnerUid());
7627 }
7628 if (shouldFilter && !newRanges.isEmpty()) {
7629 mPermissionMonitor.onVpnUidRangesAdded(iface, newRanges, newNc.getOwnerUid());
7630 }
7631 } catch (Exception e) {
7632 // Never crash!
7633 loge("Exception in updateUids: ", e);
7634 }
7635 }
7636
7637 public void handleUpdateLinkProperties(NetworkAgentInfo nai, LinkProperties newLp) {
7638 ensureRunningOnConnectivityServiceThread();
7639
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09007640 if (!mNetworkAgentInfos.contains(nai)) {
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00007641 // Ignore updates for disconnected networks
7642 return;
7643 }
7644 if (VDBG || DDBG) {
7645 log("Update of LinkProperties for " + nai.toShortString()
7646 + "; created=" + nai.created
7647 + "; everConnected=" + nai.everConnected);
7648 }
7649 // TODO: eliminate this defensive copy after confirming that updateLinkProperties does not
7650 // modify its oldLp parameter.
7651 updateLinkProperties(nai, newLp, new LinkProperties(nai.linkProperties));
7652 }
7653
7654 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
7655 int notificationType) {
7656 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
7657 Intent intent = new Intent();
7658 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
7659 // If apps could file multi-layer requests with PendingIntents, they'd need to know
7660 // which of the layer is satisfied alongside with some ID for the request. Hence, if
7661 // such an API is ever implemented, there is no doubt the right request to send in
Remi NGUYEN VAN1e238a82021-06-25 16:38:05 +09007662 // EXTRA_NETWORK_REQUEST is the active request, and whatever ID would be added would
7663 // need to be sent as a separate extra.
7664 final NetworkRequest req = nri.isMultilayerRequest()
7665 ? nri.getActiveRequest()
7666 // Non-multilayer listen requests do not have an active request
7667 : nri.mRequests.get(0);
7668 if (req == null) {
7669 Log.wtf(TAG, "No request in NRI " + nri);
7670 }
7671 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, req);
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00007672 nri.mPendingIntentSent = true;
7673 sendIntent(nri.mPendingIntent, intent);
7674 }
7675 // else not handled
7676 }
7677
7678 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
7679 mPendingIntentWakeLock.acquire();
7680 try {
7681 if (DBG) log("Sending " + pendingIntent);
7682 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
7683 } catch (PendingIntent.CanceledException e) {
7684 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
7685 mPendingIntentWakeLock.release();
7686 releasePendingNetworkRequest(pendingIntent);
7687 }
7688 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
7689 }
7690
7691 @Override
7692 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
7693 String resultData, Bundle resultExtras) {
7694 if (DBG) log("Finished sending " + pendingIntent);
7695 mPendingIntentWakeLock.release();
7696 // Release with a delay so the receiving client has an opportunity to put in its
7697 // own request.
7698 releasePendingNetworkRequestWithDelay(pendingIntent);
7699 }
7700
7701 private void callCallbackForRequest(@NonNull final NetworkRequestInfo nri,
7702 @NonNull final NetworkAgentInfo networkAgent, final int notificationType,
7703 final int arg1) {
7704 if (nri.mMessenger == null) {
7705 // Default request has no msgr. Also prevents callbacks from being invoked for
7706 // NetworkRequestInfos registered with ConnectivityDiagnostics requests. Those callbacks
7707 // are Type.LISTEN, but should not have NetworkCallbacks invoked.
7708 return;
7709 }
7710 Bundle bundle = new Bundle();
7711 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
7712 // TODO: check if defensive copies of data is needed.
7713 final NetworkRequest nrForCallback = nri.getNetworkRequestForCallback();
7714 putParcelable(bundle, nrForCallback);
7715 Message msg = Message.obtain();
7716 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
7717 putParcelable(bundle, networkAgent.network);
7718 }
7719 final boolean includeLocationSensitiveInfo =
7720 (nri.mCallbackFlags & NetworkCallback.FLAG_INCLUDE_LOCATION_INFO) != 0;
7721 switch (notificationType) {
7722 case ConnectivityManager.CALLBACK_AVAILABLE: {
7723 final NetworkCapabilities nc =
7724 networkCapabilitiesRestrictedForCallerPermissions(
7725 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
7726 putParcelable(
7727 bundle,
7728 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
7729 nc, includeLocationSensitiveInfo, nri.mPid, nri.mUid,
7730 nrForCallback.getRequestorPackageName(),
7731 nri.mCallingAttributionTag));
7732 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
7733 networkAgent.linkProperties, nri.mPid, nri.mUid));
7734 // For this notification, arg1 contains the blocked status.
7735 msg.arg1 = arg1;
7736 break;
7737 }
7738 case ConnectivityManager.CALLBACK_LOSING: {
7739 msg.arg1 = arg1;
7740 break;
7741 }
7742 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
7743 // networkAgent can't be null as it has been accessed a few lines above.
7744 final NetworkCapabilities netCap =
7745 networkCapabilitiesRestrictedForCallerPermissions(
7746 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
7747 putParcelable(
7748 bundle,
7749 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
7750 netCap, includeLocationSensitiveInfo, nri.mPid, nri.mUid,
7751 nrForCallback.getRequestorPackageName(),
7752 nri.mCallingAttributionTag));
7753 break;
7754 }
7755 case ConnectivityManager.CALLBACK_IP_CHANGED: {
7756 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
7757 networkAgent.linkProperties, nri.mPid, nri.mUid));
7758 break;
7759 }
7760 case ConnectivityManager.CALLBACK_BLK_CHANGED: {
7761 maybeLogBlockedStatusChanged(nri, networkAgent.network, arg1);
7762 msg.arg1 = arg1;
7763 break;
7764 }
7765 }
7766 msg.what = notificationType;
7767 msg.setData(bundle);
7768 try {
7769 if (VDBG) {
7770 String notification = ConnectivityManager.getCallbackName(notificationType);
7771 log("sending notification " + notification + " for " + nrForCallback);
7772 }
7773 nri.mMessenger.send(msg);
7774 } catch (RemoteException e) {
7775 // may occur naturally in the race of binder death.
7776 loge("RemoteException caught trying to send a callback msg for " + nrForCallback);
7777 }
7778 }
7779
7780 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
7781 bundle.putParcelable(t.getClass().getSimpleName(), t);
7782 }
7783
7784 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
7785 if (nai.numRequestNetworkRequests() != 0) {
7786 for (int i = 0; i < nai.numNetworkRequests(); i++) {
7787 NetworkRequest nr = nai.requestAt(i);
7788 // Ignore listening and track default requests.
7789 if (!nr.isRequest()) continue;
7790 loge("Dead network still had at least " + nr);
7791 break;
7792 }
7793 }
7794 nai.disconnect();
7795 }
7796
7797 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
7798 if (oldNetwork == null) {
7799 loge("Unknown NetworkAgentInfo in handleLingerComplete");
7800 return;
7801 }
7802 if (DBG) log("handleLingerComplete for " + oldNetwork.toShortString());
7803
7804 // If we get here it means that the last linger timeout for this network expired. So there
7805 // must be no other active linger timers, and we must stop lingering.
7806 oldNetwork.clearInactivityState();
7807
7808 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
7809 // Tear the network down.
7810 teardownUnneededNetwork(oldNetwork);
7811 } else {
7812 // Put the network in the background if it doesn't satisfy any foreground request.
7813 updateCapabilitiesForNetwork(oldNetwork);
7814 }
7815 }
7816
7817 private void processDefaultNetworkChanges(@NonNull final NetworkReassignment changes) {
7818 boolean isDefaultChanged = false;
7819 for (final NetworkRequestInfo defaultRequestInfo : mDefaultNetworkRequests) {
7820 final NetworkReassignment.RequestReassignment reassignment =
7821 changes.getReassignment(defaultRequestInfo);
7822 if (null == reassignment) {
7823 continue;
7824 }
7825 // reassignment only contains those instances where the satisfying network changed.
7826 isDefaultChanged = true;
7827 // Notify system services of the new default.
7828 makeDefault(defaultRequestInfo, reassignment.mOldNetwork, reassignment.mNewNetwork);
7829 }
7830
7831 if (isDefaultChanged) {
7832 // Hold a wakelock for a short time to help apps in migrating to a new default.
7833 scheduleReleaseNetworkTransitionWakelock();
7834 }
7835 }
7836
7837 private void makeDefault(@NonNull final NetworkRequestInfo nri,
7838 @Nullable final NetworkAgentInfo oldDefaultNetwork,
7839 @Nullable final NetworkAgentInfo newDefaultNetwork) {
7840 if (DBG) {
7841 log("Switching to new default network for: " + nri + " using " + newDefaultNetwork);
7842 }
7843
7844 // Fix up the NetworkCapabilities of any networks that have this network as underlying.
7845 if (newDefaultNetwork != null) {
7846 propagateUnderlyingNetworkCapabilities(newDefaultNetwork.network);
7847 }
7848
7849 // Set an app level managed default and return since further processing only applies to the
7850 // default network.
7851 if (mDefaultRequest != nri) {
7852 makeDefaultForApps(nri, oldDefaultNetwork, newDefaultNetwork);
7853 return;
7854 }
7855
7856 makeDefaultNetwork(newDefaultNetwork);
7857
7858 if (oldDefaultNetwork != null) {
7859 mLingerMonitor.noteLingerDefaultNetwork(oldDefaultNetwork, newDefaultNetwork);
7860 }
7861 mNetworkActivityTracker.updateDataActivityTracking(newDefaultNetwork, oldDefaultNetwork);
7862 handleApplyDefaultProxy(null != newDefaultNetwork
7863 ? newDefaultNetwork.linkProperties.getHttpProxy() : null);
7864 updateTcpBufferSizes(null != newDefaultNetwork
7865 ? newDefaultNetwork.linkProperties.getTcpBufferSizes() : null);
7866 notifyIfacesChangedForNetworkStats();
7867 }
7868
7869 private void makeDefaultForApps(@NonNull final NetworkRequestInfo nri,
7870 @Nullable final NetworkAgentInfo oldDefaultNetwork,
7871 @Nullable final NetworkAgentInfo newDefaultNetwork) {
7872 try {
7873 if (VDBG) {
7874 log("Setting default network for " + nri
7875 + " using UIDs " + nri.getUids()
7876 + " with old network " + (oldDefaultNetwork != null
7877 ? oldDefaultNetwork.network().getNetId() : "null")
7878 + " and new network " + (newDefaultNetwork != null
7879 ? newDefaultNetwork.network().getNetId() : "null"));
7880 }
7881 if (nri.getUids().isEmpty()) {
7882 throw new IllegalStateException("makeDefaultForApps called without specifying"
7883 + " any applications to set as the default." + nri);
7884 }
7885 if (null != newDefaultNetwork) {
paulhude2a2392021-06-09 16:11:35 +08007886 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00007887 newDefaultNetwork.network.getNetId(),
paulhude2a2392021-06-09 16:11:35 +08007888 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08007889 nri.getPreferenceOrderForNetd()));
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00007890 }
7891 if (null != oldDefaultNetwork) {
paulhude2a2392021-06-09 16:11:35 +08007892 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00007893 oldDefaultNetwork.network.getNetId(),
paulhude2a2392021-06-09 16:11:35 +08007894 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08007895 nri.getPreferenceOrderForNetd()));
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00007896 }
7897 } catch (RemoteException | ServiceSpecificException e) {
7898 loge("Exception setting app default network", e);
7899 }
7900 }
7901
7902 private void makeDefaultNetwork(@Nullable final NetworkAgentInfo newDefaultNetwork) {
7903 try {
7904 if (null != newDefaultNetwork) {
7905 mNetd.networkSetDefault(newDefaultNetwork.network.getNetId());
7906 } else {
7907 mNetd.networkClearDefault();
7908 }
7909 } catch (RemoteException | ServiceSpecificException e) {
7910 loge("Exception setting default network :" + e);
7911 }
7912 }
7913
7914 private void processListenRequests(@NonNull final NetworkAgentInfo nai) {
7915 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
7916 processNewlyLostListenRequests(nai);
7917 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
7918 processNewlySatisfiedListenRequests(nai);
7919 }
7920
7921 private void processNewlyLostListenRequests(@NonNull final NetworkAgentInfo nai) {
7922 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
7923 if (nri.isMultilayerRequest()) {
7924 continue;
7925 }
7926 final NetworkRequest nr = nri.mRequests.get(0);
7927 if (!nr.isListen()) continue;
7928 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
7929 nai.removeRequest(nr.requestId);
7930 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
7931 }
7932 }
7933 }
7934
7935 private void processNewlySatisfiedListenRequests(@NonNull final NetworkAgentInfo nai) {
7936 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
7937 if (nri.isMultilayerRequest()) {
7938 continue;
7939 }
7940 final NetworkRequest nr = nri.mRequests.get(0);
7941 if (!nr.isListen()) continue;
7942 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
7943 nai.addRequest(nr);
7944 notifyNetworkAvailable(nai, nri);
7945 }
7946 }
7947 }
7948
7949 // An accumulator class to gather the list of changes that result from a rematch.
7950 private static class NetworkReassignment {
7951 static class RequestReassignment {
7952 @NonNull public final NetworkRequestInfo mNetworkRequestInfo;
7953 @Nullable public final NetworkRequest mOldNetworkRequest;
7954 @Nullable public final NetworkRequest mNewNetworkRequest;
7955 @Nullable public final NetworkAgentInfo mOldNetwork;
7956 @Nullable public final NetworkAgentInfo mNewNetwork;
7957 RequestReassignment(@NonNull final NetworkRequestInfo networkRequestInfo,
7958 @Nullable final NetworkRequest oldNetworkRequest,
7959 @Nullable final NetworkRequest newNetworkRequest,
7960 @Nullable final NetworkAgentInfo oldNetwork,
7961 @Nullable final NetworkAgentInfo newNetwork) {
7962 mNetworkRequestInfo = networkRequestInfo;
7963 mOldNetworkRequest = oldNetworkRequest;
7964 mNewNetworkRequest = newNetworkRequest;
7965 mOldNetwork = oldNetwork;
7966 mNewNetwork = newNetwork;
7967 }
7968
7969 public String toString() {
7970 final NetworkRequest requestToShow = null != mNewNetworkRequest
7971 ? mNewNetworkRequest : mNetworkRequestInfo.mRequests.get(0);
7972 return requestToShow.requestId + " : "
7973 + (null != mOldNetwork ? mOldNetwork.network.getNetId() : "null")
7974 + " → " + (null != mNewNetwork ? mNewNetwork.network.getNetId() : "null");
7975 }
7976 }
7977
7978 @NonNull private final ArrayList<RequestReassignment> mReassignments = new ArrayList<>();
7979
7980 @NonNull Iterable<RequestReassignment> getRequestReassignments() {
7981 return mReassignments;
7982 }
7983
7984 void addRequestReassignment(@NonNull final RequestReassignment reassignment) {
7985 if (Build.isDebuggable()) {
7986 // The code is never supposed to add two reassignments of the same request. Make
7987 // sure this stays true, but without imposing this expensive check on all
7988 // reassignments on all user devices.
7989 for (final RequestReassignment existing : mReassignments) {
7990 if (existing.mNetworkRequestInfo.equals(reassignment.mNetworkRequestInfo)) {
7991 throw new IllegalStateException("Trying to reassign ["
7992 + reassignment + "] but already have ["
7993 + existing + "]");
7994 }
7995 }
7996 }
7997 mReassignments.add(reassignment);
7998 }
7999
8000 // Will return null if this reassignment does not change the network assigned to
8001 // the passed request.
8002 @Nullable
8003 private RequestReassignment getReassignment(@NonNull final NetworkRequestInfo nri) {
8004 for (final RequestReassignment event : getRequestReassignments()) {
8005 if (nri == event.mNetworkRequestInfo) return event;
8006 }
8007 return null;
8008 }
8009
8010 public String toString() {
8011 final StringJoiner sj = new StringJoiner(", " /* delimiter */,
8012 "NetReassign [" /* prefix */, "]" /* suffix */);
8013 if (mReassignments.isEmpty()) return sj.add("no changes").toString();
8014 for (final RequestReassignment rr : getRequestReassignments()) {
8015 sj.add(rr.toString());
8016 }
8017 return sj.toString();
8018 }
8019
8020 public String debugString() {
8021 final StringBuilder sb = new StringBuilder();
8022 sb.append("NetworkReassignment :");
8023 if (mReassignments.isEmpty()) return sb.append(" no changes").toString();
8024 for (final RequestReassignment rr : getRequestReassignments()) {
8025 sb.append("\n ").append(rr);
8026 }
8027 return sb.append("\n").toString();
8028 }
8029 }
8030
8031 private void updateSatisfiersForRematchRequest(@NonNull final NetworkRequestInfo nri,
8032 @Nullable final NetworkRequest previousRequest,
8033 @Nullable final NetworkRequest newRequest,
8034 @Nullable final NetworkAgentInfo previousSatisfier,
8035 @Nullable final NetworkAgentInfo newSatisfier,
8036 final long now) {
8037 if (null != newSatisfier && mNoServiceNetwork != newSatisfier) {
8038 if (VDBG) log("rematch for " + newSatisfier.toShortString());
8039 if (null != previousRequest && null != previousSatisfier) {
8040 if (VDBG || DDBG) {
8041 log(" accepting network in place of " + previousSatisfier.toShortString());
8042 }
8043 previousSatisfier.removeRequest(previousRequest.requestId);
8044 previousSatisfier.lingerRequest(previousRequest.requestId, now);
8045 } else {
8046 if (VDBG || DDBG) log(" accepting network in place of null");
8047 }
8048
8049 // To prevent constantly CPU wake up for nascent timer, if a network comes up
8050 // and immediately satisfies a request then remove the timer. This will happen for
8051 // all networks except in the case of an underlying network for a VCN.
8052 if (newSatisfier.isNascent()) {
8053 newSatisfier.unlingerRequest(NetworkRequest.REQUEST_ID_NONE);
8054 newSatisfier.unsetInactive();
8055 }
8056
8057 // if newSatisfier is not null, then newRequest may not be null.
8058 newSatisfier.unlingerRequest(newRequest.requestId);
8059 if (!newSatisfier.addRequest(newRequest)) {
8060 Log.wtf(TAG, "BUG: " + newSatisfier.toShortString() + " already has "
8061 + newRequest);
8062 }
8063 } else if (null != previousRequest && null != previousSatisfier) {
8064 if (DBG) {
8065 log("Network " + previousSatisfier.toShortString() + " stopped satisfying"
8066 + " request " + previousRequest.requestId);
8067 }
8068 previousSatisfier.removeRequest(previousRequest.requestId);
8069 }
8070 nri.setSatisfier(newSatisfier, newRequest);
8071 }
8072
8073 /**
8074 * This function is triggered when something can affect what network should satisfy what
8075 * request, and it computes the network reassignment from the passed collection of requests to
8076 * network match to the one that the system should now have. That data is encoded in an
8077 * object that is a list of changes, each of them having an NRI, and old satisfier, and a new
8078 * satisfier.
8079 *
8080 * After the reassignment is computed, it is applied to the state objects.
8081 *
8082 * @param networkRequests the nri objects to evaluate for possible network reassignment
8083 * @return NetworkReassignment listing of proposed network assignment changes
8084 */
8085 @NonNull
8086 private NetworkReassignment computeNetworkReassignment(
8087 @NonNull final Collection<NetworkRequestInfo> networkRequests) {
8088 final NetworkReassignment changes = new NetworkReassignment();
8089
8090 // Gather the list of all relevant agents.
8091 final ArrayList<NetworkAgentInfo> nais = new ArrayList<>();
8092 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
8093 if (!nai.everConnected) {
8094 continue;
8095 }
8096 nais.add(nai);
8097 }
8098
8099 for (final NetworkRequestInfo nri : networkRequests) {
8100 // Non-multilayer listen requests can be ignored.
8101 if (!nri.isMultilayerRequest() && nri.mRequests.get(0).isListen()) {
8102 continue;
8103 }
8104 NetworkAgentInfo bestNetwork = null;
8105 NetworkRequest bestRequest = null;
8106 for (final NetworkRequest req : nri.mRequests) {
8107 bestNetwork = mNetworkRanker.getBestNetwork(req, nais, nri.getSatisfier());
8108 // Stop evaluating as the highest possible priority request is satisfied.
8109 if (null != bestNetwork) {
8110 bestRequest = req;
8111 break;
8112 }
8113 }
8114 if (null == bestNetwork && isDefaultBlocked(nri)) {
8115 // Remove default networking if disallowed for managed default requests.
8116 bestNetwork = mNoServiceNetwork;
8117 }
8118 if (nri.getSatisfier() != bestNetwork) {
8119 // bestNetwork may be null if no network can satisfy this request.
8120 changes.addRequestReassignment(new NetworkReassignment.RequestReassignment(
8121 nri, nri.mActiveRequest, bestRequest, nri.getSatisfier(), bestNetwork));
8122 }
8123 }
8124 return changes;
8125 }
8126
8127 private Set<NetworkRequestInfo> getNrisFromGlobalRequests() {
8128 return new HashSet<>(mNetworkRequests.values());
8129 }
8130
8131 /**
8132 * Attempt to rematch all Networks with all NetworkRequests. This may result in Networks
8133 * being disconnected.
8134 */
8135 private void rematchAllNetworksAndRequests() {
8136 rematchNetworksAndRequests(getNrisFromGlobalRequests());
8137 }
8138
8139 /**
8140 * Attempt to rematch all Networks with given NetworkRequests. This may result in Networks
8141 * being disconnected.
8142 */
8143 private void rematchNetworksAndRequests(
8144 @NonNull final Set<NetworkRequestInfo> networkRequests) {
8145 ensureRunningOnConnectivityServiceThread();
8146 // TODO: This may be slow, and should be optimized.
8147 final long now = SystemClock.elapsedRealtime();
8148 final NetworkReassignment changes = computeNetworkReassignment(networkRequests);
8149 if (VDBG || DDBG) {
8150 log(changes.debugString());
8151 } else if (DBG) {
8152 log(changes.toString()); // Shorter form, only one line of log
8153 }
8154 applyNetworkReassignment(changes, now);
8155 issueNetworkNeeds();
8156 }
8157
8158 private void applyNetworkReassignment(@NonNull final NetworkReassignment changes,
8159 final long now) {
8160 final Collection<NetworkAgentInfo> nais = mNetworkAgentInfos;
8161
8162 // Since most of the time there are only 0 or 1 background networks, it would probably
8163 // be more efficient to just use an ArrayList here. TODO : measure performance
8164 final ArraySet<NetworkAgentInfo> oldBgNetworks = new ArraySet<>();
8165 for (final NetworkAgentInfo nai : nais) {
8166 if (nai.isBackgroundNetwork()) oldBgNetworks.add(nai);
8167 }
8168
8169 // First, update the lists of satisfied requests in the network agents. This is necessary
8170 // because some code later depends on this state to be correct, most prominently computing
8171 // the linger status.
8172 for (final NetworkReassignment.RequestReassignment event :
8173 changes.getRequestReassignments()) {
8174 updateSatisfiersForRematchRequest(event.mNetworkRequestInfo,
8175 event.mOldNetworkRequest, event.mNewNetworkRequest,
8176 event.mOldNetwork, event.mNewNetwork,
8177 now);
8178 }
8179
8180 // Process default network changes if applicable.
8181 processDefaultNetworkChanges(changes);
8182
8183 // Notify requested networks are available after the default net is switched, but
8184 // before LegacyTypeTracker sends legacy broadcasts
8185 for (final NetworkReassignment.RequestReassignment event :
8186 changes.getRequestReassignments()) {
8187 if (null != event.mNewNetwork) {
8188 notifyNetworkAvailable(event.mNewNetwork, event.mNetworkRequestInfo);
8189 } else {
8190 callCallbackForRequest(event.mNetworkRequestInfo, event.mOldNetwork,
8191 ConnectivityManager.CALLBACK_LOST, 0);
8192 }
8193 }
8194
8195 // Update the inactivity state before processing listen callbacks, because the background
8196 // computation depends on whether the network is inactive. Don't send the LOSING callbacks
8197 // just yet though, because they have to be sent after the listens are processed to keep
8198 // backward compatibility.
8199 final ArrayList<NetworkAgentInfo> inactiveNetworks = new ArrayList<>();
8200 for (final NetworkAgentInfo nai : nais) {
8201 // Rematching may have altered the inactivity state of some networks, so update all
8202 // inactivity timers. updateInactivityState reads the state from the network agent
8203 // and does nothing if the state has not changed : the source of truth is controlled
8204 // with NetworkAgentInfo#lingerRequest and NetworkAgentInfo#unlingerRequest, which
8205 // have been called while rematching the individual networks above.
8206 if (updateInactivityState(nai, now)) {
8207 inactiveNetworks.add(nai);
8208 }
8209 }
8210
8211 for (final NetworkAgentInfo nai : nais) {
8212 if (!nai.everConnected) continue;
8213 final boolean oldBackground = oldBgNetworks.contains(nai);
8214 // Process listen requests and update capabilities if the background state has
8215 // changed for this network. For consistency with previous behavior, send onLost
8216 // callbacks before onAvailable.
8217 processNewlyLostListenRequests(nai);
8218 if (oldBackground != nai.isBackgroundNetwork()) {
8219 applyBackgroundChangeForRematch(nai);
8220 }
8221 processNewlySatisfiedListenRequests(nai);
8222 }
8223
8224 for (final NetworkAgentInfo nai : inactiveNetworks) {
8225 // For nascent networks, if connecting with no foreground request, skip broadcasting
8226 // LOSING for backward compatibility. This is typical when mobile data connected while
8227 // wifi connected with mobile data always-on enabled.
8228 if (nai.isNascent()) continue;
8229 notifyNetworkLosing(nai, now);
8230 }
8231
8232 updateLegacyTypeTrackerAndVpnLockdownForRematch(changes, nais);
8233
8234 // Tear down all unneeded networks.
8235 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
8236 if (unneeded(nai, UnneededFor.TEARDOWN)) {
8237 if (nai.getInactivityExpiry() > 0) {
8238 // This network has active linger timers and no requests, but is not
8239 // lingering. Linger it.
8240 //
8241 // One way (the only way?) this can happen if this network is unvalidated
8242 // and became unneeded due to another network improving its score to the
8243 // point where this network will no longer be able to satisfy any requests
8244 // even if it validates.
8245 if (updateInactivityState(nai, now)) {
8246 notifyNetworkLosing(nai, now);
8247 }
8248 } else {
8249 if (DBG) log("Reaping " + nai.toShortString());
8250 teardownUnneededNetwork(nai);
8251 }
8252 }
8253 }
8254 }
8255
8256 /**
8257 * Apply a change in background state resulting from rematching networks with requests.
8258 *
8259 * During rematch, a network may change background states by starting to satisfy or stopping
8260 * to satisfy a foreground request. Listens don't count for this. When a network changes
8261 * background states, its capabilities need to be updated and callbacks fired for the
8262 * capability change.
8263 *
8264 * @param nai The network that changed background states
8265 */
8266 private void applyBackgroundChangeForRematch(@NonNull final NetworkAgentInfo nai) {
8267 final NetworkCapabilities newNc = mixInCapabilities(nai, nai.networkCapabilities);
8268 if (Objects.equals(nai.networkCapabilities, newNc)) return;
8269 updateNetworkPermissions(nai, newNc);
8270 nai.getAndSetNetworkCapabilities(newNc);
8271 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
8272 }
8273
8274 private void updateLegacyTypeTrackerAndVpnLockdownForRematch(
8275 @NonNull final NetworkReassignment changes,
8276 @NonNull final Collection<NetworkAgentInfo> nais) {
8277 final NetworkReassignment.RequestReassignment reassignmentOfDefault =
8278 changes.getReassignment(mDefaultRequest);
8279 final NetworkAgentInfo oldDefaultNetwork =
8280 null != reassignmentOfDefault ? reassignmentOfDefault.mOldNetwork : null;
8281 final NetworkAgentInfo newDefaultNetwork =
8282 null != reassignmentOfDefault ? reassignmentOfDefault.mNewNetwork : null;
8283
8284 if (oldDefaultNetwork != newDefaultNetwork) {
8285 // Maintain the illusion : since the legacy API only understands one network at a time,
8286 // if the default network changed, apps should see a disconnected broadcast for the
8287 // old default network before they see a connected broadcast for the new one.
8288 if (oldDefaultNetwork != null) {
8289 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
8290 oldDefaultNetwork, true);
8291 }
8292 if (newDefaultNetwork != null) {
8293 // The new default network can be newly null if and only if the old default
8294 // network doesn't satisfy the default request any more because it lost a
8295 // capability.
8296 mDefaultInetConditionPublished = newDefaultNetwork.lastValidated ? 100 : 0;
8297 mLegacyTypeTracker.add(
8298 newDefaultNetwork.networkInfo.getType(), newDefaultNetwork);
8299 }
8300 }
8301
8302 // Now that all the callbacks have been sent, send the legacy network broadcasts
8303 // as needed. This is necessary so that legacy requests correctly bind dns
8304 // requests to this network. The legacy users are listening for this broadcast
8305 // and will generally do a dns request so they can ensureRouteToHost and if
8306 // they do that before the callbacks happen they'll use the default network.
8307 //
8308 // TODO: Is there still a race here? The legacy broadcast will be sent after sending
8309 // callbacks, but if apps can receive the broadcast before the callback, they still might
8310 // have an inconsistent view of networking.
8311 //
8312 // This *does* introduce a race where if the user uses the new api
8313 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
8314 // they may get old info. Reverse this after the old startUsing api is removed.
8315 // This is on top of the multiple intent sequencing referenced in the todo above.
8316 for (NetworkAgentInfo nai : nais) {
8317 if (nai.everConnected) {
8318 addNetworkToLegacyTypeTracker(nai);
8319 }
8320 }
8321 }
8322
8323 private void issueNetworkNeeds() {
8324 ensureRunningOnConnectivityServiceThread();
8325 for (final NetworkOfferInfo noi : mNetworkOffers) {
8326 issueNetworkNeeds(noi);
8327 }
8328 }
8329
8330 private void issueNetworkNeeds(@NonNull final NetworkOfferInfo noi) {
8331 ensureRunningOnConnectivityServiceThread();
8332 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
8333 informOffer(nri, noi.offer, mNetworkRanker);
8334 }
8335 }
8336
8337 /**
8338 * Inform a NetworkOffer about any new situation of a request.
8339 *
8340 * This function handles updates to offers. A number of events may happen that require
8341 * updating the registrant for this offer about the situation :
8342 * • The offer itself was updated. This may lead the offer to no longer being able
8343 * to satisfy a request or beat a satisfier (and therefore be no longer needed),
8344 * or conversely being strengthened enough to beat the satisfier (and therefore
8345 * start being needed)
8346 * • The network satisfying a request changed (including cases where the request
8347 * starts or stops being satisfied). The new network may be a stronger or weaker
8348 * match than the old one, possibly affecting whether the offer is needed.
8349 * • The network satisfying a request updated their score. This may lead the offer
8350 * to no longer be able to beat it if the current satisfier got better, or
8351 * conversely start being a good choice if the current satisfier got weaker.
8352 *
8353 * @param nri The request
8354 * @param offer The offer. This may be an updated offer.
8355 */
8356 private static void informOffer(@NonNull NetworkRequestInfo nri,
8357 @NonNull final NetworkOffer offer, @NonNull final NetworkRanker networkRanker) {
8358 final NetworkRequest activeRequest = nri.isBeingSatisfied() ? nri.getActiveRequest() : null;
8359 final NetworkAgentInfo satisfier = null != activeRequest ? nri.getSatisfier() : null;
8360
8361 // Multi-layer requests have a currently active request, the one being satisfied.
8362 // Since the system will try to bring up a better network than is currently satisfying
8363 // the request, NetworkProviders need to be told the offers matching the requests *above*
8364 // the currently satisfied one are needed, that the ones *below* the satisfied one are
8365 // not needed, and the offer is needed for the active request iff the offer can beat
8366 // the satisfier.
8367 // For non-multilayer requests, the logic above gracefully degenerates to only the
8368 // last case.
8369 // To achieve this, the loop below will proceed in three steps. In a first phase, inform
8370 // providers that the offer is needed for this request, until the active request is found.
8371 // In a second phase, deal with the currently active request. In a third phase, inform
8372 // the providers that offer is unneeded for the remaining requests.
8373
8374 // First phase : inform providers of all requests above the active request.
8375 int i;
8376 for (i = 0; nri.mRequests.size() > i; ++i) {
8377 final NetworkRequest request = nri.mRequests.get(i);
8378 if (activeRequest == request) break; // Found the active request : go to phase 2
8379 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
8380 // Since this request is higher-priority than the one currently satisfied, if the
8381 // offer can satisfy it, the provider should try and bring up the network for sure ;
8382 // no need to even ask the ranker – an offer that can satisfy is always better than
8383 // no network. Hence tell the provider so unless it already knew.
8384 if (request.canBeSatisfiedBy(offer.caps) && !offer.neededFor(request)) {
8385 offer.onNetworkNeeded(request);
8386 }
8387 }
8388
8389 // Second phase : deal with the active request (if any)
8390 if (null != activeRequest && activeRequest.isRequest()) {
8391 final boolean oldNeeded = offer.neededFor(activeRequest);
Junyu Laidc3a7a32021-05-26 12:23:56 +00008392 // If an offer can satisfy the request, it is considered needed if it is currently
8393 // served by this provider or if this offer can beat the current satisfier.
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00008394 final boolean currentlyServing = satisfier != null
Junyu Laidc3a7a32021-05-26 12:23:56 +00008395 && satisfier.factorySerialNumber == offer.providerId
8396 && activeRequest.canBeSatisfiedBy(offer.caps);
8397 final boolean newNeeded = currentlyServing
8398 || networkRanker.mightBeat(activeRequest, satisfier, offer);
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00008399 if (newNeeded != oldNeeded) {
8400 if (newNeeded) {
8401 offer.onNetworkNeeded(activeRequest);
8402 } else {
8403 // The offer used to be able to beat the satisfier. Now it can't.
8404 offer.onNetworkUnneeded(activeRequest);
8405 }
8406 }
8407 }
8408
8409 // Third phase : inform the providers that the offer isn't needed for any request
8410 // below the active one.
8411 for (++i /* skip the active request */; nri.mRequests.size() > i; ++i) {
8412 final NetworkRequest request = nri.mRequests.get(i);
8413 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
8414 // Since this request is lower-priority than the one currently satisfied, if the
8415 // offer can satisfy it, the provider should not try and bring up the network.
8416 // Hence tell the provider so unless it already knew.
8417 if (offer.neededFor(request)) {
8418 offer.onNetworkUnneeded(request);
8419 }
8420 }
8421 }
8422
8423 private void addNetworkToLegacyTypeTracker(@NonNull final NetworkAgentInfo nai) {
8424 for (int i = 0; i < nai.numNetworkRequests(); i++) {
8425 NetworkRequest nr = nai.requestAt(i);
8426 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
8427 // legacy type tracker filters out repeat adds
8428 mLegacyTypeTracker.add(nr.legacyType, nai);
8429 }
8430 }
8431
8432 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
8433 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
8434 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
8435 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
8436 if (nai.isVPN()) {
8437 mLegacyTypeTracker.add(TYPE_VPN, nai);
8438 }
8439 }
8440
8441 private void updateInetCondition(NetworkAgentInfo nai) {
8442 // Don't bother updating until we've graduated to validated at least once.
8443 if (!nai.everValidated) return;
8444 // For now only update icons for the default connection.
8445 // TODO: Update WiFi and cellular icons separately. b/17237507
8446 if (!isDefaultNetwork(nai)) return;
8447
8448 int newInetCondition = nai.lastValidated ? 100 : 0;
8449 // Don't repeat publish.
8450 if (newInetCondition == mDefaultInetConditionPublished) return;
8451
8452 mDefaultInetConditionPublished = newInetCondition;
8453 sendInetConditionBroadcast(nai.networkInfo);
8454 }
8455
8456 @NonNull
8457 private NetworkInfo mixInInfo(@NonNull final NetworkAgentInfo nai, @NonNull NetworkInfo info) {
8458 final NetworkInfo newInfo = new NetworkInfo(info);
8459 // The suspended and roaming bits are managed in NetworkCapabilities.
8460 final boolean suspended =
8461 !nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
8462 if (suspended && info.getDetailedState() == NetworkInfo.DetailedState.CONNECTED) {
8463 // Only override the state with SUSPENDED if the network is currently in CONNECTED
8464 // state. This is because the network could have been suspended before connecting,
8465 // or it could be disconnecting while being suspended, and in both these cases
8466 // the state should not be overridden. Note that the only detailed state that
8467 // maps to State.CONNECTED is DetailedState.CONNECTED, so there is also no need to
8468 // worry about multiple different substates of CONNECTED.
8469 newInfo.setDetailedState(NetworkInfo.DetailedState.SUSPENDED, info.getReason(),
8470 info.getExtraInfo());
8471 } else if (!suspended && info.getDetailedState() == NetworkInfo.DetailedState.SUSPENDED) {
8472 // SUSPENDED state is currently only overridden from CONNECTED state. In the case the
8473 // network agent is created, then goes to suspended, then goes out of suspended without
8474 // ever setting connected. Check if network agent is ever connected to update the state.
8475 newInfo.setDetailedState(nai.everConnected
8476 ? NetworkInfo.DetailedState.CONNECTED
8477 : NetworkInfo.DetailedState.CONNECTING,
8478 info.getReason(),
8479 info.getExtraInfo());
8480 }
8481 newInfo.setRoaming(!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_ROAMING));
8482 return newInfo;
8483 }
8484
8485 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo info) {
8486 final NetworkInfo newInfo = mixInInfo(networkAgent, info);
8487
8488 final NetworkInfo.State state = newInfo.getState();
8489 NetworkInfo oldInfo = null;
8490 synchronized (networkAgent) {
8491 oldInfo = networkAgent.networkInfo;
8492 networkAgent.networkInfo = newInfo;
8493 }
8494
8495 if (DBG) {
8496 log(networkAgent.toShortString() + " EVENT_NETWORK_INFO_CHANGED, going from "
8497 + oldInfo.getState() + " to " + state);
8498 }
8499
8500 if (!networkAgent.created
8501 && (state == NetworkInfo.State.CONNECTED
8502 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
8503
8504 // A network that has just connected has zero requests and is thus a foreground network.
8505 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
8506
8507 if (!createNativeNetwork(networkAgent)) return;
Lorenzo Colittibd079452021-07-02 11:47:57 +09008508 if (networkAgent.propagateUnderlyingCapabilities()) {
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00008509 // Initialize the network's capabilities to their starting values according to the
8510 // underlying networks. This ensures that the capabilities are correct before
8511 // anything happens to the network.
8512 updateCapabilitiesForNetwork(networkAgent);
8513 }
8514 networkAgent.created = true;
8515 networkAgent.onNetworkCreated();
8516 }
8517
8518 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
8519 networkAgent.everConnected = true;
8520
8521 // NetworkCapabilities need to be set before sending the private DNS config to
8522 // NetworkMonitor, otherwise NetworkMonitor cannot determine if validation is required.
8523 networkAgent.getAndSetNetworkCapabilities(networkAgent.networkCapabilities);
8524
8525 handlePerNetworkPrivateDnsConfig(networkAgent, mDnsManager.getPrivateDnsConfig());
8526 updateLinkProperties(networkAgent, new LinkProperties(networkAgent.linkProperties),
8527 null);
8528
8529 // Until parceled LinkProperties are sent directly to NetworkMonitor, the connect
8530 // command must be sent after updating LinkProperties to maximize chances of
8531 // NetworkMonitor seeing the correct LinkProperties when starting.
8532 // TODO: pass LinkProperties to the NetworkMonitor in the notifyNetworkConnected call.
8533 if (networkAgent.networkAgentConfig.acceptPartialConnectivity) {
8534 networkAgent.networkMonitor().setAcceptPartialConnectivity();
8535 }
8536 networkAgent.networkMonitor().notifyNetworkConnected(
8537 new LinkProperties(networkAgent.linkProperties,
8538 true /* parcelSensitiveFields */),
8539 networkAgent.networkCapabilities);
8540 scheduleUnvalidatedPrompt(networkAgent);
8541
8542 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
8543 // be communicated to a particular NetworkAgent depends only on the network's immutable,
8544 // capabilities, so it only needs to be done once on initial connect, not every time the
8545 // network's capabilities change. Note that we do this before rematching the network,
8546 // so we could decide to tear it down immediately afterwards. That's fine though - on
8547 // disconnection NetworkAgents should stop any signal strength monitoring they have been
8548 // doing.
8549 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
8550
8551 // Before first rematching networks, put an inactivity timer without any request, this
8552 // allows {@code updateInactivityState} to update the state accordingly and prevent
8553 // tearing down for any {@code unneeded} evaluation in this period.
8554 // Note that the timer will not be rescheduled since the expiry time is
8555 // fixed after connection regardless of the network satisfying other requests or not.
8556 // But it will be removed as soon as the network satisfies a request for the first time.
8557 networkAgent.lingerRequest(NetworkRequest.REQUEST_ID_NONE,
8558 SystemClock.elapsedRealtime(), mNascentDelayMs);
8559 networkAgent.setInactive();
8560
8561 // Consider network even though it is not yet validated.
8562 rematchAllNetworksAndRequests();
8563
8564 // This has to happen after matching the requests, because callbacks are just requests.
8565 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
8566 } else if (state == NetworkInfo.State.DISCONNECTED) {
8567 networkAgent.disconnect();
8568 if (networkAgent.isVPN()) {
8569 updateUids(networkAgent, networkAgent.networkCapabilities, null);
8570 }
8571 disconnectAndDestroyNetwork(networkAgent);
8572 if (networkAgent.isVPN()) {
8573 // As the active or bound network changes for apps, broadcast the default proxy, as
8574 // apps may need to update their proxy data. This is called after disconnecting from
8575 // VPN to make sure we do not broadcast the old proxy data.
8576 // TODO(b/122649188): send the broadcast only to VPN users.
8577 mProxyTracker.sendProxyBroadcast();
8578 }
8579 } else if (networkAgent.created && (oldInfo.getState() == NetworkInfo.State.SUSPENDED ||
8580 state == NetworkInfo.State.SUSPENDED)) {
8581 mLegacyTypeTracker.update(networkAgent);
8582 }
8583 }
8584
8585 private void updateNetworkScore(@NonNull final NetworkAgentInfo nai, final NetworkScore score) {
8586 if (VDBG || DDBG) log("updateNetworkScore for " + nai.toShortString() + " to " + score);
8587 nai.setScore(score);
8588 rematchAllNetworksAndRequests();
8589 }
8590
8591 // Notify only this one new request of the current state. Transfer all the
8592 // current state by calling NetworkCapabilities and LinkProperties callbacks
8593 // so that callers can be guaranteed to have as close to atomicity in state
8594 // transfer as can be supported by this current API.
8595 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
8596 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
8597 if (nri.mPendingIntent != null) {
8598 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
8599 // Attempt no subsequent state pushes where intents are involved.
8600 return;
8601 }
8602
8603 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
8604 final boolean metered = nai.networkCapabilities.isMetered();
8605 final boolean vpnBlocked = isUidBlockedByVpn(nri.mAsUid, mVpnBlockedUidRanges);
8606 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE,
8607 getBlockedState(blockedReasons, metered, vpnBlocked));
8608 }
8609
8610 // Notify the requests on this NAI that the network is now lingered.
8611 private void notifyNetworkLosing(@NonNull final NetworkAgentInfo nai, final long now) {
8612 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
8613 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
8614 }
8615
8616 private static int getBlockedState(int reasons, boolean metered, boolean vpnBlocked) {
8617 if (!metered) reasons &= ~BLOCKED_METERED_REASON_MASK;
8618 return vpnBlocked
8619 ? reasons | BLOCKED_REASON_LOCKDOWN_VPN
8620 : reasons & ~BLOCKED_REASON_LOCKDOWN_VPN;
8621 }
8622
8623 private void setUidBlockedReasons(int uid, @BlockedReason int blockedReasons) {
8624 if (blockedReasons == BLOCKED_REASON_NONE) {
8625 mUidBlockedReasons.delete(uid);
8626 } else {
8627 mUidBlockedReasons.put(uid, blockedReasons);
8628 }
8629 }
8630
8631 /**
8632 * Notify of the blocked state apps with a registered callback matching a given NAI.
8633 *
8634 * Unlike other callbacks, blocked status is different between each individual uid. So for
8635 * any given nai, all requests need to be considered according to the uid who filed it.
8636 *
8637 * @param nai The target NetworkAgentInfo.
8638 * @param oldMetered True if the previous network capabilities were metered.
8639 * @param newMetered True if the current network capabilities are metered.
8640 * @param oldBlockedUidRanges list of UID ranges previously blocked by lockdown VPN.
8641 * @param newBlockedUidRanges list of UID ranges blocked by lockdown VPN.
8642 */
8643 private void maybeNotifyNetworkBlocked(NetworkAgentInfo nai, boolean oldMetered,
8644 boolean newMetered, List<UidRange> oldBlockedUidRanges,
8645 List<UidRange> newBlockedUidRanges) {
8646
8647 for (int i = 0; i < nai.numNetworkRequests(); i++) {
8648 NetworkRequest nr = nai.requestAt(i);
8649 NetworkRequestInfo nri = mNetworkRequests.get(nr);
8650
8651 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
8652 final boolean oldVpnBlocked = isUidBlockedByVpn(nri.mAsUid, oldBlockedUidRanges);
8653 final boolean newVpnBlocked = (oldBlockedUidRanges != newBlockedUidRanges)
8654 ? isUidBlockedByVpn(nri.mAsUid, newBlockedUidRanges)
8655 : oldVpnBlocked;
8656
8657 final int oldBlockedState = getBlockedState(blockedReasons, oldMetered, oldVpnBlocked);
8658 final int newBlockedState = getBlockedState(blockedReasons, newMetered, newVpnBlocked);
8659 if (oldBlockedState != newBlockedState) {
8660 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
8661 newBlockedState);
8662 }
8663 }
8664 }
8665
8666 /**
8667 * Notify apps with a given UID of the new blocked state according to new uid state.
8668 * @param uid The uid for which the rules changed.
8669 * @param blockedReasons The reasons for why an uid is blocked.
8670 */
8671 private void maybeNotifyNetworkBlockedForNewState(int uid, @BlockedReason int blockedReasons) {
8672 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
8673 final boolean metered = nai.networkCapabilities.isMetered();
8674 final boolean vpnBlocked = isUidBlockedByVpn(uid, mVpnBlockedUidRanges);
8675
8676 final int oldBlockedState = getBlockedState(
8677 mUidBlockedReasons.get(uid, BLOCKED_REASON_NONE), metered, vpnBlocked);
8678 final int newBlockedState = getBlockedState(blockedReasons, metered, vpnBlocked);
8679 if (oldBlockedState == newBlockedState) {
8680 continue;
8681 }
8682 for (int i = 0; i < nai.numNetworkRequests(); i++) {
8683 NetworkRequest nr = nai.requestAt(i);
8684 NetworkRequestInfo nri = mNetworkRequests.get(nr);
8685 if (nri != null && nri.mAsUid == uid) {
8686 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
8687 newBlockedState);
8688 }
8689 }
8690 }
8691 }
8692
8693 @VisibleForTesting
8694 protected void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
8695 // The NetworkInfo we actually send out has no bearing on the real
8696 // state of affairs. For example, if the default connection is mobile,
8697 // and a request for HIPRI has just gone away, we need to pretend that
8698 // HIPRI has just disconnected. So we need to set the type to HIPRI and
8699 // the state to DISCONNECTED, even though the network is of type MOBILE
8700 // and is still connected.
8701 NetworkInfo info = new NetworkInfo(nai.networkInfo);
8702 info.setType(type);
8703 filterForLegacyLockdown(info);
8704 if (state != DetailedState.DISCONNECTED) {
8705 info.setDetailedState(state, null, info.getExtraInfo());
8706 sendConnectedBroadcast(info);
8707 } else {
8708 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
8709 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
8710 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
8711 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
8712 if (info.isFailover()) {
8713 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
8714 nai.networkInfo.setFailover(false);
8715 }
8716 if (info.getReason() != null) {
8717 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
8718 }
8719 if (info.getExtraInfo() != null) {
8720 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
8721 }
8722 NetworkAgentInfo newDefaultAgent = null;
8723 if (nai.isSatisfyingRequest(mDefaultRequest.mRequests.get(0).requestId)) {
8724 newDefaultAgent = mDefaultRequest.getSatisfier();
8725 if (newDefaultAgent != null) {
8726 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
8727 newDefaultAgent.networkInfo);
8728 } else {
8729 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
8730 }
8731 }
8732 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
8733 mDefaultInetConditionPublished);
8734 sendStickyBroadcast(intent);
8735 if (newDefaultAgent != null) {
8736 sendConnectedBroadcast(newDefaultAgent.networkInfo);
8737 }
8738 }
8739 }
8740
8741 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
8742 if (VDBG || DDBG) {
8743 String notification = ConnectivityManager.getCallbackName(notifyType);
8744 log("notifyType " + notification + " for " + networkAgent.toShortString());
8745 }
8746 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
8747 NetworkRequest nr = networkAgent.requestAt(i);
8748 NetworkRequestInfo nri = mNetworkRequests.get(nr);
8749 if (VDBG) log(" sending notification for " + nr);
8750 if (nri.mPendingIntent == null) {
8751 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
8752 } else {
8753 sendPendingIntentForRequest(nri, networkAgent, notifyType);
8754 }
8755 }
8756 }
8757
8758 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
8759 notifyNetworkCallbacks(networkAgent, notifyType, 0);
8760 }
8761
8762 /**
8763 * Returns the list of all interfaces that could be used by network traffic that does not
8764 * explicitly specify a network. This includes the default network, but also all VPNs that are
8765 * currently connected.
8766 *
8767 * Must be called on the handler thread.
8768 */
8769 @NonNull
8770 private ArrayList<Network> getDefaultNetworks() {
8771 ensureRunningOnConnectivityServiceThread();
8772 final ArrayList<Network> defaultNetworks = new ArrayList<>();
8773 final Set<Integer> activeNetIds = new ArraySet<>();
8774 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
8775 if (nri.isBeingSatisfied()) {
8776 activeNetIds.add(nri.getSatisfier().network().netId);
8777 }
8778 }
8779 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
8780 if (nai.everConnected && (activeNetIds.contains(nai.network().netId) || nai.isVPN())) {
8781 defaultNetworks.add(nai.network);
8782 }
8783 }
8784 return defaultNetworks;
8785 }
8786
8787 /**
8788 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
8789 * active iface's tracked properties has changed.
8790 */
8791 private void notifyIfacesChangedForNetworkStats() {
8792 ensureRunningOnConnectivityServiceThread();
8793 String activeIface = null;
8794 LinkProperties activeLinkProperties = getActiveLinkProperties();
8795 if (activeLinkProperties != null) {
8796 activeIface = activeLinkProperties.getInterfaceName();
8797 }
8798
8799 final UnderlyingNetworkInfo[] underlyingNetworkInfos = getAllVpnInfo();
8800 try {
8801 final ArrayList<NetworkStateSnapshot> snapshots = new ArrayList<>();
junyulai0f570222021-03-05 14:46:25 +08008802 for (final NetworkStateSnapshot snapshot : getAllNetworkStateSnapshots()) {
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00008803 snapshots.add(snapshot);
8804 }
8805 mStatsManager.notifyNetworkStatus(getDefaultNetworks(),
8806 snapshots, activeIface, Arrays.asList(underlyingNetworkInfos));
8807 } catch (Exception ignored) {
8808 }
8809 }
8810
8811 @Override
8812 public String getCaptivePortalServerUrl() {
8813 enforceNetworkStackOrSettingsPermission();
8814 String settingUrl = mResources.get().getString(
8815 R.string.config_networkCaptivePortalServerUrl);
8816
8817 if (!TextUtils.isEmpty(settingUrl)) {
8818 return settingUrl;
8819 }
8820
8821 settingUrl = Settings.Global.getString(mContext.getContentResolver(),
8822 ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL);
8823 if (!TextUtils.isEmpty(settingUrl)) {
8824 return settingUrl;
8825 }
8826
8827 return DEFAULT_CAPTIVE_PORTAL_HTTP_URL;
8828 }
8829
8830 @Override
8831 public void startNattKeepalive(Network network, int intervalSeconds,
8832 ISocketKeepaliveCallback cb, String srcAddr, int srcPort, String dstAddr) {
8833 enforceKeepalivePermission();
8834 mKeepaliveTracker.startNattKeepalive(
8835 getNetworkAgentInfoForNetwork(network), null /* fd */,
8836 intervalSeconds, cb,
8837 srcAddr, srcPort, dstAddr, NattSocketKeepalive.NATT_PORT);
8838 }
8839
8840 @Override
8841 public void startNattKeepaliveWithFd(Network network, ParcelFileDescriptor pfd, int resourceId,
8842 int intervalSeconds, ISocketKeepaliveCallback cb, String srcAddr,
8843 String dstAddr) {
8844 try {
8845 final FileDescriptor fd = pfd.getFileDescriptor();
8846 mKeepaliveTracker.startNattKeepalive(
8847 getNetworkAgentInfoForNetwork(network), fd, resourceId,
8848 intervalSeconds, cb,
8849 srcAddr, dstAddr, NattSocketKeepalive.NATT_PORT);
8850 } finally {
8851 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
8852 // startNattKeepalive calls Os.dup(fd) before returning, so we can close immediately.
8853 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
8854 IoUtils.closeQuietly(pfd);
8855 }
8856 }
8857 }
8858
8859 @Override
8860 public void startTcpKeepalive(Network network, ParcelFileDescriptor pfd, int intervalSeconds,
8861 ISocketKeepaliveCallback cb) {
8862 try {
8863 enforceKeepalivePermission();
8864 final FileDescriptor fd = pfd.getFileDescriptor();
8865 mKeepaliveTracker.startTcpKeepalive(
8866 getNetworkAgentInfoForNetwork(network), fd, intervalSeconds, cb);
8867 } finally {
8868 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
8869 // startTcpKeepalive calls Os.dup(fd) before returning, so we can close immediately.
8870 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
8871 IoUtils.closeQuietly(pfd);
8872 }
8873 }
8874 }
8875
8876 @Override
8877 public void stopKeepalive(Network network, int slot) {
8878 mHandler.sendMessage(mHandler.obtainMessage(
8879 NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE, slot, SocketKeepalive.SUCCESS, network));
8880 }
8881
8882 @Override
8883 public void factoryReset() {
8884 enforceSettingsPermission();
8885
Treehugger Robotfac2a722021-05-21 02:42:59 +00008886 final int uid = mDeps.getCallingUid();
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00008887 final long token = Binder.clearCallingIdentity();
8888 try {
Treehugger Robotfac2a722021-05-21 02:42:59 +00008889 if (mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_NETWORK_RESET,
8890 UserHandle.getUserHandleForUid(uid))) {
8891 return;
8892 }
8893
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00008894 final IpMemoryStore ipMemoryStore = IpMemoryStore.getMemoryStore(mContext);
8895 ipMemoryStore.factoryReset();
Treehugger Robotfac2a722021-05-21 02:42:59 +00008896
8897 // Turn airplane mode off
8898 setAirplaneMode(false);
8899
8900 // restore private DNS settings to default mode (opportunistic)
8901 if (!mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_CONFIG_PRIVATE_DNS,
8902 UserHandle.getUserHandleForUid(uid))) {
8903 ConnectivitySettingsManager.setPrivateDnsMode(mContext,
8904 PRIVATE_DNS_MODE_OPPORTUNISTIC);
8905 }
8906
8907 Settings.Global.putString(mContext.getContentResolver(),
8908 ConnectivitySettingsManager.NETWORK_AVOID_BAD_WIFI, null);
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00008909 } finally {
8910 Binder.restoreCallingIdentity(token);
8911 }
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00008912 }
8913
8914 @Override
8915 public byte[] getNetworkWatchlistConfigHash() {
8916 NetworkWatchlistManager nwm = mContext.getSystemService(NetworkWatchlistManager.class);
8917 if (nwm == null) {
8918 loge("Unable to get NetworkWatchlistManager");
8919 return null;
8920 }
8921 // Redirect it to network watchlist service to access watchlist file and calculate hash.
8922 return nwm.getWatchlistConfigHash();
8923 }
8924
8925 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
8926 int[] transports = nai.networkCapabilities.getTransportTypes();
8927 mMetricsLog.log(nai.network.getNetId(), transports, new NetworkEvent(evtype));
8928 }
8929
8930 private static boolean toBool(int encodedBoolean) {
8931 return encodedBoolean != 0; // Only 0 means false.
8932 }
8933
8934 private static int encodeBool(boolean b) {
8935 return b ? 1 : 0;
8936 }
8937
8938 @Override
8939 public int handleShellCommand(@NonNull ParcelFileDescriptor in,
8940 @NonNull ParcelFileDescriptor out, @NonNull ParcelFileDescriptor err,
8941 @NonNull String[] args) {
8942 return new ShellCmd().exec(this, in.getFileDescriptor(), out.getFileDescriptor(),
8943 err.getFileDescriptor(), args);
8944 }
8945
8946 private class ShellCmd extends BasicShellCommandHandler {
8947 @Override
8948 public int onCommand(String cmd) {
8949 if (cmd == null) {
8950 return handleDefaultCommands(cmd);
8951 }
8952 final PrintWriter pw = getOutPrintWriter();
8953 try {
8954 switch (cmd) {
8955 case "airplane-mode":
8956 final String action = getNextArg();
8957 if ("enable".equals(action)) {
8958 setAirplaneMode(true);
8959 return 0;
8960 } else if ("disable".equals(action)) {
8961 setAirplaneMode(false);
8962 return 0;
8963 } else if (action == null) {
8964 final ContentResolver cr = mContext.getContentResolver();
8965 final int enabled = Settings.Global.getInt(cr,
8966 Settings.Global.AIRPLANE_MODE_ON);
8967 pw.println(enabled == 0 ? "disabled" : "enabled");
8968 return 0;
8969 } else {
8970 onHelp();
8971 return -1;
8972 }
8973 default:
8974 return handleDefaultCommands(cmd);
8975 }
8976 } catch (Exception e) {
8977 pw.println(e);
8978 }
8979 return -1;
8980 }
8981
8982 @Override
8983 public void onHelp() {
8984 PrintWriter pw = getOutPrintWriter();
8985 pw.println("Connectivity service commands:");
8986 pw.println(" help");
8987 pw.println(" Print this help text.");
8988 pw.println(" airplane-mode [enable|disable]");
8989 pw.println(" Turn airplane mode on or off.");
8990 pw.println(" airplane-mode");
8991 pw.println(" Get airplane mode.");
8992 }
8993 }
8994
8995 private int getVpnType(@Nullable NetworkAgentInfo vpn) {
8996 if (vpn == null) return VpnManager.TYPE_VPN_NONE;
8997 final TransportInfo ti = vpn.networkCapabilities.getTransportInfo();
8998 if (!(ti instanceof VpnTransportInfo)) return VpnManager.TYPE_VPN_NONE;
8999 return ((VpnTransportInfo) ti).getType();
9000 }
9001
9002 /**
9003 * @param connectionInfo the connection to resolve.
9004 * @return {@code uid} if the connection is found and the app has permission to observe it
9005 * (e.g., if it is associated with the calling VPN app's tunnel) or {@code INVALID_UID} if the
9006 * connection is not found.
9007 */
9008 public int getConnectionOwnerUid(ConnectionInfo connectionInfo) {
9009 if (connectionInfo.protocol != IPPROTO_TCP && connectionInfo.protocol != IPPROTO_UDP) {
9010 throw new IllegalArgumentException("Unsupported protocol " + connectionInfo.protocol);
9011 }
9012
9013 final int uid = mDeps.getConnectionOwnerUid(connectionInfo.protocol,
9014 connectionInfo.local, connectionInfo.remote);
9015
9016 if (uid == INVALID_UID) return uid; // Not found.
9017
9018 // Connection owner UIDs are visible only to the network stack and to the VpnService-based
9019 // VPN, if any, that applies to the UID that owns the connection.
9020 if (checkNetworkStackPermission()) return uid;
9021
9022 final NetworkAgentInfo vpn = getVpnForUid(uid);
9023 if (vpn == null || getVpnType(vpn) != VpnManager.TYPE_VPN_SERVICE
9024 || vpn.networkCapabilities.getOwnerUid() != mDeps.getCallingUid()) {
9025 return INVALID_UID;
9026 }
9027
9028 return uid;
9029 }
9030
9031 /**
9032 * Returns a IBinder to a TestNetworkService. Will be lazily created as needed.
9033 *
9034 * <p>The TestNetworkService must be run in the system server due to TUN creation.
9035 */
9036 @Override
9037 public IBinder startOrGetTestNetworkService() {
9038 synchronized (mTNSLock) {
9039 TestNetworkService.enforceTestNetworkPermissions(mContext);
9040
9041 if (mTNS == null) {
9042 mTNS = new TestNetworkService(mContext);
9043 }
9044
9045 return mTNS;
9046 }
9047 }
9048
9049 /**
9050 * Handler used for managing all Connectivity Diagnostics related functions.
9051 *
9052 * @see android.net.ConnectivityDiagnosticsManager
9053 *
9054 * TODO(b/147816404): Explore moving ConnectivityDiagnosticsHandler to a separate file
9055 */
9056 @VisibleForTesting
9057 class ConnectivityDiagnosticsHandler extends Handler {
9058 private final String mTag = ConnectivityDiagnosticsHandler.class.getSimpleName();
9059
9060 /**
9061 * Used to handle ConnectivityDiagnosticsCallback registration events from {@link
9062 * android.net.ConnectivityDiagnosticsManager}.
9063 * obj = ConnectivityDiagnosticsCallbackInfo with IConnectivityDiagnosticsCallback and
9064 * NetworkRequestInfo to be registered
9065 */
9066 private static final int EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 1;
9067
9068 /**
9069 * Used to handle ConnectivityDiagnosticsCallback unregister events from {@link
9070 * android.net.ConnectivityDiagnosticsManager}.
9071 * obj = the IConnectivityDiagnosticsCallback to be unregistered
9072 * arg1 = the uid of the caller
9073 */
9074 private static final int EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 2;
9075
9076 /**
9077 * Event for {@link NetworkStateTrackerHandler} to trigger ConnectivityReport callbacks
9078 * after processing {@link #EVENT_NETWORK_TESTED} events.
9079 * obj = {@link ConnectivityReportEvent} representing ConnectivityReport info reported from
9080 * NetworkMonitor.
9081 * data = PersistableBundle of extras passed from NetworkMonitor.
9082 *
9083 * <p>See {@link ConnectivityService#EVENT_NETWORK_TESTED}.
9084 */
9085 private static final int EVENT_NETWORK_TESTED = ConnectivityService.EVENT_NETWORK_TESTED;
9086
9087 /**
9088 * Event for NetworkMonitor to inform ConnectivityService that a potential data stall has
9089 * been detected on the network.
9090 * obj = Long the timestamp (in millis) for when the suspected data stall was detected.
9091 * arg1 = {@link DataStallReport#DetectionMethod} indicating the detection method.
9092 * arg2 = NetID.
9093 * data = PersistableBundle of extras passed from NetworkMonitor.
9094 */
9095 private static final int EVENT_DATA_STALL_SUSPECTED = 4;
9096
9097 /**
9098 * Event for ConnectivityDiagnosticsHandler to handle network connectivity being reported to
9099 * the platform. This event will invoke {@link
9100 * IConnectivityDiagnosticsCallback#onNetworkConnectivityReported} for permissioned
9101 * callbacks.
Cody Kestingf1120be2020-08-03 18:01:40 -07009102 * obj = ReportedNetworkConnectivityInfo with info on reported Network connectivity.
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00009103 */
9104 private static final int EVENT_NETWORK_CONNECTIVITY_REPORTED = 5;
9105
9106 private ConnectivityDiagnosticsHandler(Looper looper) {
9107 super(looper);
9108 }
9109
9110 @Override
9111 public void handleMessage(Message msg) {
9112 switch (msg.what) {
9113 case EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
9114 handleRegisterConnectivityDiagnosticsCallback(
9115 (ConnectivityDiagnosticsCallbackInfo) msg.obj);
9116 break;
9117 }
9118 case EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
9119 handleUnregisterConnectivityDiagnosticsCallback(
9120 (IConnectivityDiagnosticsCallback) msg.obj, msg.arg1);
9121 break;
9122 }
9123 case EVENT_NETWORK_TESTED: {
9124 final ConnectivityReportEvent reportEvent =
9125 (ConnectivityReportEvent) msg.obj;
9126
9127 handleNetworkTestedWithExtras(reportEvent, reportEvent.mExtras);
9128 break;
9129 }
9130 case EVENT_DATA_STALL_SUSPECTED: {
9131 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
9132 final Pair<Long, PersistableBundle> arg =
9133 (Pair<Long, PersistableBundle>) msg.obj;
9134 if (nai == null) break;
9135
9136 handleDataStallSuspected(nai, arg.first, msg.arg1, arg.second);
9137 break;
9138 }
9139 case EVENT_NETWORK_CONNECTIVITY_REPORTED: {
Cody Kestingf1120be2020-08-03 18:01:40 -07009140 handleNetworkConnectivityReported((ReportedNetworkConnectivityInfo) msg.obj);
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00009141 break;
9142 }
9143 default: {
9144 Log.e(mTag, "Unrecognized event in ConnectivityDiagnostics: " + msg.what);
9145 }
9146 }
9147 }
9148 }
9149
9150 /** Class used for cleaning up IConnectivityDiagnosticsCallback instances after their death. */
9151 @VisibleForTesting
9152 class ConnectivityDiagnosticsCallbackInfo implements Binder.DeathRecipient {
9153 @NonNull private final IConnectivityDiagnosticsCallback mCb;
9154 @NonNull private final NetworkRequestInfo mRequestInfo;
9155 @NonNull private final String mCallingPackageName;
9156
9157 @VisibleForTesting
9158 ConnectivityDiagnosticsCallbackInfo(
9159 @NonNull IConnectivityDiagnosticsCallback cb,
9160 @NonNull NetworkRequestInfo nri,
9161 @NonNull String callingPackageName) {
9162 mCb = cb;
9163 mRequestInfo = nri;
9164 mCallingPackageName = callingPackageName;
9165 }
9166
9167 @Override
9168 public void binderDied() {
9169 log("ConnectivityDiagnosticsCallback IBinder died.");
9170 unregisterConnectivityDiagnosticsCallback(mCb);
9171 }
9172 }
9173
9174 /**
9175 * Class used for sending information from {@link
9176 * NetworkMonitorCallbacks#notifyNetworkTestedWithExtras} to the handler for processing it.
9177 */
9178 private static class NetworkTestedResults {
9179 private final int mNetId;
9180 private final int mTestResult;
9181 private final long mTimestampMillis;
9182 @Nullable private final String mRedirectUrl;
9183
9184 private NetworkTestedResults(
9185 int netId, int testResult, long timestampMillis, @Nullable String redirectUrl) {
9186 mNetId = netId;
9187 mTestResult = testResult;
9188 mTimestampMillis = timestampMillis;
9189 mRedirectUrl = redirectUrl;
9190 }
9191 }
9192
9193 /**
9194 * Class used for sending information from {@link NetworkStateTrackerHandler} to {@link
9195 * ConnectivityDiagnosticsHandler}.
9196 */
9197 private static class ConnectivityReportEvent {
9198 private final long mTimestampMillis;
9199 @NonNull private final NetworkAgentInfo mNai;
9200 private final PersistableBundle mExtras;
9201
9202 private ConnectivityReportEvent(long timestampMillis, @NonNull NetworkAgentInfo nai,
9203 PersistableBundle p) {
9204 mTimestampMillis = timestampMillis;
9205 mNai = nai;
9206 mExtras = p;
9207 }
9208 }
9209
Cody Kestingf1120be2020-08-03 18:01:40 -07009210 /**
9211 * Class used for sending info for a call to {@link #reportNetworkConnectivity()} to {@link
9212 * ConnectivityDiagnosticsHandler}.
9213 */
9214 private static class ReportedNetworkConnectivityInfo {
9215 public final boolean hasConnectivity;
9216 public final boolean isNetworkRevalidating;
9217 public final int reporterUid;
9218 @NonNull public final NetworkAgentInfo nai;
9219
9220 private ReportedNetworkConnectivityInfo(
9221 boolean hasConnectivity,
9222 boolean isNetworkRevalidating,
9223 int reporterUid,
9224 @NonNull NetworkAgentInfo nai) {
9225 this.hasConnectivity = hasConnectivity;
9226 this.isNetworkRevalidating = isNetworkRevalidating;
9227 this.reporterUid = reporterUid;
9228 this.nai = nai;
9229 }
9230 }
9231
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00009232 private void handleRegisterConnectivityDiagnosticsCallback(
9233 @NonNull ConnectivityDiagnosticsCallbackInfo cbInfo) {
9234 ensureRunningOnConnectivityServiceThread();
9235
9236 final IConnectivityDiagnosticsCallback cb = cbInfo.mCb;
9237 final IBinder iCb = cb.asBinder();
9238 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
9239
9240 // Connectivity Diagnostics are meant to be used with a single network request. It would be
9241 // confusing for these networks to change when an NRI is satisfied in another layer.
9242 if (nri.isMultilayerRequest()) {
9243 throw new IllegalArgumentException("Connectivity Diagnostics do not support multilayer "
9244 + "network requests.");
9245 }
9246
9247 // This means that the client registered the same callback multiple times. Do
9248 // not override the previous entry, and exit silently.
9249 if (mConnectivityDiagnosticsCallbacks.containsKey(iCb)) {
9250 if (VDBG) log("Diagnostics callback is already registered");
9251
9252 // Decrement the reference count for this NetworkRequestInfo. The reference count is
9253 // incremented when the NetworkRequestInfo is created as part of
9254 // enforceRequestCountLimit().
9255 nri.decrementRequestCount();
9256 return;
9257 }
9258
9259 mConnectivityDiagnosticsCallbacks.put(iCb, cbInfo);
9260
9261 try {
9262 iCb.linkToDeath(cbInfo, 0);
9263 } catch (RemoteException e) {
9264 cbInfo.binderDied();
9265 return;
9266 }
9267
9268 // Once registered, provide ConnectivityReports for matching Networks
9269 final List<NetworkAgentInfo> matchingNetworks = new ArrayList<>();
9270 synchronized (mNetworkForNetId) {
9271 for (int i = 0; i < mNetworkForNetId.size(); i++) {
9272 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
9273 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0)
9274 if (nai.satisfies(nri.mRequests.get(0))) {
9275 matchingNetworks.add(nai);
9276 }
9277 }
9278 }
9279 for (final NetworkAgentInfo nai : matchingNetworks) {
9280 final ConnectivityReport report = nai.getConnectivityReport();
9281 if (report == null) {
9282 continue;
9283 }
9284 if (!checkConnectivityDiagnosticsPermissions(
9285 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
9286 continue;
9287 }
9288
9289 try {
9290 cb.onConnectivityReportAvailable(report);
9291 } catch (RemoteException e) {
9292 // Exception while sending the ConnectivityReport. Move on to the next network.
9293 }
9294 }
9295 }
9296
9297 private void handleUnregisterConnectivityDiagnosticsCallback(
9298 @NonNull IConnectivityDiagnosticsCallback cb, int uid) {
9299 ensureRunningOnConnectivityServiceThread();
9300 final IBinder iCb = cb.asBinder();
9301
9302 final ConnectivityDiagnosticsCallbackInfo cbInfo =
9303 mConnectivityDiagnosticsCallbacks.remove(iCb);
9304 if (cbInfo == null) {
9305 if (VDBG) log("Removing diagnostics callback that is not currently registered");
9306 return;
9307 }
9308
9309 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
9310
9311 // Caller's UID must either be the registrants (if they are unregistering) or the System's
9312 // (if the Binder died)
9313 if (uid != nri.mUid && uid != Process.SYSTEM_UID) {
9314 if (DBG) loge("Uid(" + uid + ") not registrant's (" + nri.mUid + ") or System's");
9315 return;
9316 }
9317
9318 // Decrement the reference count for this NetworkRequestInfo. The reference count is
9319 // incremented when the NetworkRequestInfo is created as part of
9320 // enforceRequestCountLimit().
9321 nri.decrementRequestCount();
9322
9323 iCb.unlinkToDeath(cbInfo, 0);
9324 }
9325
9326 private void handleNetworkTestedWithExtras(
9327 @NonNull ConnectivityReportEvent reportEvent, @NonNull PersistableBundle extras) {
9328 final NetworkAgentInfo nai = reportEvent.mNai;
9329 final NetworkCapabilities networkCapabilities =
9330 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
9331 final ConnectivityReport report =
9332 new ConnectivityReport(
9333 reportEvent.mNai.network,
9334 reportEvent.mTimestampMillis,
9335 nai.linkProperties,
9336 networkCapabilities,
9337 extras);
9338 nai.setConnectivityReport(report);
Cody Kestingf1120be2020-08-03 18:01:40 -07009339
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00009340 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -07009341 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00009342 for (final IConnectivityDiagnosticsCallback cb : results) {
9343 try {
9344 cb.onConnectivityReportAvailable(report);
9345 } catch (RemoteException ex) {
Cody Kestingf1120be2020-08-03 18:01:40 -07009346 loge("Error invoking onConnectivityReportAvailable", ex);
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00009347 }
9348 }
9349 }
9350
9351 private void handleDataStallSuspected(
9352 @NonNull NetworkAgentInfo nai, long timestampMillis, int detectionMethod,
9353 @NonNull PersistableBundle extras) {
9354 final NetworkCapabilities networkCapabilities =
9355 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
9356 final DataStallReport report =
9357 new DataStallReport(
9358 nai.network,
9359 timestampMillis,
9360 detectionMethod,
9361 nai.linkProperties,
9362 networkCapabilities,
9363 extras);
9364 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -07009365 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00009366 for (final IConnectivityDiagnosticsCallback cb : results) {
9367 try {
9368 cb.onDataStallSuspected(report);
9369 } catch (RemoteException ex) {
9370 loge("Error invoking onDataStallSuspected", ex);
9371 }
9372 }
9373 }
9374
9375 private void handleNetworkConnectivityReported(
Cody Kestingf1120be2020-08-03 18:01:40 -07009376 @NonNull ReportedNetworkConnectivityInfo reportedNetworkConnectivityInfo) {
9377 final NetworkAgentInfo nai = reportedNetworkConnectivityInfo.nai;
9378 final ConnectivityReport cachedReport = nai.getConnectivityReport();
9379
9380 // If the Network is being re-validated as a result of this call to
9381 // reportNetworkConnectivity(), notify all permissioned callbacks. Otherwise, only notify
9382 // permissioned callbacks registered by the reporter.
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00009383 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -07009384 getMatchingPermissionedCallbacks(
9385 nai,
9386 reportedNetworkConnectivityInfo.isNetworkRevalidating
9387 ? Process.INVALID_UID
9388 : reportedNetworkConnectivityInfo.reporterUid);
9389
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00009390 for (final IConnectivityDiagnosticsCallback cb : results) {
9391 try {
Cody Kestingf1120be2020-08-03 18:01:40 -07009392 cb.onNetworkConnectivityReported(
9393 nai.network, reportedNetworkConnectivityInfo.hasConnectivity);
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00009394 } catch (RemoteException ex) {
9395 loge("Error invoking onNetworkConnectivityReported", ex);
9396 }
Cody Kestingf1120be2020-08-03 18:01:40 -07009397
9398 // If the Network isn't re-validating, also provide the cached report. If there is no
9399 // cached report, the Network is still being validated and a report will be sent once
9400 // validation is complete. Note that networks which never undergo validation will still
9401 // have a cached ConnectivityReport with RESULT_SKIPPED.
9402 if (!reportedNetworkConnectivityInfo.isNetworkRevalidating && cachedReport != null) {
9403 try {
9404 cb.onConnectivityReportAvailable(cachedReport);
9405 } catch (RemoteException ex) {
9406 loge("Error invoking onConnectivityReportAvailable", ex);
9407 }
9408 }
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00009409 }
9410 }
9411
9412 private NetworkCapabilities getNetworkCapabilitiesWithoutUids(@NonNull NetworkCapabilities nc) {
9413 final NetworkCapabilities sanitized = new NetworkCapabilities(nc,
9414 NetworkCapabilities.REDACT_ALL);
9415 sanitized.setUids(null);
9416 sanitized.setAdministratorUids(new int[0]);
9417 sanitized.setOwnerUid(Process.INVALID_UID);
9418 return sanitized;
9419 }
9420
Cody Kestingf1120be2020-08-03 18:01:40 -07009421 /**
9422 * Gets a list of ConnectivityDiagnostics callbacks that match the specified Network and uid.
9423 *
9424 * <p>If Process.INVALID_UID is specified, all matching callbacks will be returned.
9425 */
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00009426 private List<IConnectivityDiagnosticsCallback> getMatchingPermissionedCallbacks(
Cody Kestingf1120be2020-08-03 18:01:40 -07009427 @NonNull NetworkAgentInfo nai, int uid) {
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00009428 final List<IConnectivityDiagnosticsCallback> results = new ArrayList<>();
9429 for (Entry<IBinder, ConnectivityDiagnosticsCallbackInfo> entry :
9430 mConnectivityDiagnosticsCallbacks.entrySet()) {
9431 final ConnectivityDiagnosticsCallbackInfo cbInfo = entry.getValue();
9432 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kestingf1120be2020-08-03 18:01:40 -07009433
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00009434 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0).
Cody Kestingf1120be2020-08-03 18:01:40 -07009435 if (!nai.satisfies(nri.mRequests.get(0))) {
9436 continue;
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00009437 }
Cody Kestingf1120be2020-08-03 18:01:40 -07009438
9439 // UID for this callback must either be:
9440 // - INVALID_UID (which sends callbacks to all UIDs), or
9441 // - The callback's owner (the owner called reportNetworkConnectivity() and is being
9442 // notified as a result)
9443 if (uid != Process.INVALID_UID && uid != nri.mUid) {
9444 continue;
9445 }
9446
9447 if (!checkConnectivityDiagnosticsPermissions(
9448 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
9449 continue;
9450 }
9451
9452 results.add(entry.getValue().mCb);
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00009453 }
9454 return results;
9455 }
9456
Cody Kesting7474f672021-05-11 14:22:40 -07009457 private boolean isLocationPermissionRequiredForConnectivityDiagnostics(
9458 @NonNull NetworkAgentInfo nai) {
9459 // TODO(b/188483916): replace with a transport-agnostic location-aware check
9460 return nai.networkCapabilities.hasTransport(TRANSPORT_WIFI);
9461 }
9462
Cody Kesting0b4be022021-05-20 22:57:07 +00009463 private boolean hasLocationPermission(String packageName, int uid) {
9464 // LocationPermissionChecker#checkLocationPermission can throw SecurityException if the uid
9465 // and package name don't match. Throwing on the CS thread is not acceptable, so wrap the
9466 // call in a try-catch.
9467 try {
9468 if (!mLocationPermissionChecker.checkLocationPermission(
9469 packageName, null /* featureId */, uid, null /* message */)) {
9470 return false;
9471 }
9472 } catch (SecurityException e) {
9473 return false;
9474 }
9475
9476 return true;
9477 }
9478
9479 private boolean ownsVpnRunningOverNetwork(int uid, Network network) {
9480 for (NetworkAgentInfo virtual : mNetworkAgentInfos) {
Lorenzo Colittibd079452021-07-02 11:47:57 +09009481 if (virtual.propagateUnderlyingCapabilities()
Cody Kesting0b4be022021-05-20 22:57:07 +00009482 && virtual.networkCapabilities.getOwnerUid() == uid
9483 && CollectionUtils.contains(virtual.declaredUnderlyingNetworks, network)) {
9484 return true;
9485 }
9486 }
9487
9488 return false;
9489 }
9490
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00009491 @VisibleForTesting
9492 boolean checkConnectivityDiagnosticsPermissions(
9493 int callbackPid, int callbackUid, NetworkAgentInfo nai, String callbackPackageName) {
9494 if (checkNetworkStackPermission(callbackPid, callbackUid)) {
9495 return true;
9496 }
9497
Cody Kesting0b4be022021-05-20 22:57:07 +00009498 // Administrator UIDs also contains the Owner UID
9499 final int[] administratorUids = nai.networkCapabilities.getAdministratorUids();
9500 if (!CollectionUtils.contains(administratorUids, callbackUid)
9501 && !ownsVpnRunningOverNetwork(callbackUid, nai.network)) {
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00009502 return false;
9503 }
9504
Cody Kesting7474f672021-05-11 14:22:40 -07009505 return !isLocationPermissionRequiredForConnectivityDiagnostics(nai)
9506 || hasLocationPermission(callbackPackageName, callbackUid);
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00009507 }
9508
9509 @Override
9510 public void registerConnectivityDiagnosticsCallback(
9511 @NonNull IConnectivityDiagnosticsCallback callback,
9512 @NonNull NetworkRequest request,
9513 @NonNull String callingPackageName) {
9514 if (request.legacyType != TYPE_NONE) {
9515 throw new IllegalArgumentException("ConnectivityManager.TYPE_* are deprecated."
9516 + " Please use NetworkCapabilities instead.");
9517 }
9518 final int callingUid = mDeps.getCallingUid();
9519 mAppOpsManager.checkPackage(callingUid, callingPackageName);
9520
9521 // This NetworkCapabilities is only used for matching to Networks. Clear out its owner uid
9522 // and administrator uids to be safe.
9523 final NetworkCapabilities nc = new NetworkCapabilities(request.networkCapabilities);
9524 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
9525
9526 final NetworkRequest requestWithId =
9527 new NetworkRequest(
9528 nc, TYPE_NONE, nextNetworkRequestId(), NetworkRequest.Type.LISTEN);
9529
9530 // NetworkRequestInfos created here count towards MAX_NETWORK_REQUESTS_PER_UID limit.
9531 //
9532 // nri is not bound to the death of callback. Instead, callback.bindToDeath() is set in
9533 // handleRegisterConnectivityDiagnosticsCallback(). nri will be cleaned up as part of the
9534 // callback's binder death.
9535 final NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, requestWithId);
9536 final ConnectivityDiagnosticsCallbackInfo cbInfo =
9537 new ConnectivityDiagnosticsCallbackInfo(callback, nri, callingPackageName);
9538
9539 mConnectivityDiagnosticsHandler.sendMessage(
9540 mConnectivityDiagnosticsHandler.obtainMessage(
9541 ConnectivityDiagnosticsHandler
9542 .EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
9543 cbInfo));
9544 }
9545
9546 @Override
9547 public void unregisterConnectivityDiagnosticsCallback(
9548 @NonNull IConnectivityDiagnosticsCallback callback) {
9549 Objects.requireNonNull(callback, "callback must be non-null");
9550 mConnectivityDiagnosticsHandler.sendMessage(
9551 mConnectivityDiagnosticsHandler.obtainMessage(
9552 ConnectivityDiagnosticsHandler
9553 .EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
9554 mDeps.getCallingUid(),
9555 0,
9556 callback));
9557 }
9558
9559 @Override
9560 public void simulateDataStall(int detectionMethod, long timestampMillis,
9561 @NonNull Network network, @NonNull PersistableBundle extras) {
9562 enforceAnyPermissionOf(android.Manifest.permission.MANAGE_TEST_NETWORKS,
9563 android.Manifest.permission.NETWORK_STACK);
9564 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
9565 if (!nc.hasTransport(TRANSPORT_TEST)) {
9566 throw new SecurityException("Data Stall simluation is only possible for test networks");
9567 }
9568
9569 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
9570 if (nai == null || nai.creatorUid != mDeps.getCallingUid()) {
9571 throw new SecurityException("Data Stall simulation is only possible for network "
9572 + "creators");
9573 }
9574
9575 // Instead of passing the data stall directly to the ConnectivityDiagnostics handler, treat
9576 // this as a Data Stall received directly from NetworkMonitor. This requires wrapping the
9577 // Data Stall information as a DataStallReportParcelable and passing to
9578 // #notifyDataStallSuspected. This ensures that unknown Data Stall detection methods are
9579 // still passed to ConnectivityDiagnostics (with new detection methods masked).
9580 final DataStallReportParcelable p = new DataStallReportParcelable();
9581 p.timestampMillis = timestampMillis;
9582 p.detectionMethod = detectionMethod;
9583
9584 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
9585 p.dnsConsecutiveTimeouts = extras.getInt(KEY_DNS_CONSECUTIVE_TIMEOUTS);
9586 }
9587 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
9588 p.tcpPacketFailRate = extras.getInt(KEY_TCP_PACKET_FAIL_RATE);
9589 p.tcpMetricsCollectionPeriodMillis = extras.getInt(
9590 KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS);
9591 }
9592
9593 notifyDataStallSuspected(p, network.getNetId());
9594 }
9595
9596 private class NetdCallback extends BaseNetdUnsolicitedEventListener {
9597 @Override
9598 public void onInterfaceClassActivityChanged(boolean isActive, int transportType,
9599 long timestampNs, int uid) {
9600 mNetworkActivityTracker.setAndReportNetworkActive(isActive, transportType, timestampNs);
9601 }
9602
9603 @Override
9604 public void onInterfaceLinkStateChanged(String iface, boolean up) {
9605 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
9606 nai.clatd.interfaceLinkStateChanged(iface, up);
9607 }
9608 }
9609
9610 @Override
9611 public void onInterfaceRemoved(String iface) {
9612 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
9613 nai.clatd.interfaceRemoved(iface);
9614 }
9615 }
9616 }
9617
9618 private final LegacyNetworkActivityTracker mNetworkActivityTracker;
9619
9620 /**
9621 * Class used for updating network activity tracking with netd and notify network activity
9622 * changes.
9623 */
9624 private static final class LegacyNetworkActivityTracker {
9625 private static final int NO_UID = -1;
9626 private final Context mContext;
9627 private final INetd mNetd;
9628 private final RemoteCallbackList<INetworkActivityListener> mNetworkActivityListeners =
9629 new RemoteCallbackList<>();
9630 // Indicate the current system default network activity is active or not.
9631 @GuardedBy("mActiveIdleTimers")
9632 private boolean mNetworkActive;
9633 @GuardedBy("mActiveIdleTimers")
9634 private final ArrayMap<String, IdleTimerParams> mActiveIdleTimers = new ArrayMap();
9635 private final Handler mHandler;
9636
9637 private class IdleTimerParams {
9638 public final int timeout;
9639 public final int transportType;
9640
9641 IdleTimerParams(int timeout, int transport) {
9642 this.timeout = timeout;
9643 this.transportType = transport;
9644 }
9645 }
9646
9647 LegacyNetworkActivityTracker(@NonNull Context context, @NonNull Handler handler,
9648 @NonNull INetd netd) {
9649 mContext = context;
9650 mNetd = netd;
9651 mHandler = handler;
9652 }
9653
9654 public void setAndReportNetworkActive(boolean active, int transportType, long tsNanos) {
9655 sendDataActivityBroadcast(transportTypeToLegacyType(transportType), active, tsNanos);
9656 synchronized (mActiveIdleTimers) {
9657 mNetworkActive = active;
9658 // If there are no idle timers, it means that system is not monitoring
9659 // activity, so the system default network for those default network
9660 // unspecified apps is always considered active.
9661 //
9662 // TODO: If the mActiveIdleTimers is empty, netd will actually not send
9663 // any network activity change event. Whenever this event is received,
9664 // the mActiveIdleTimers should be always not empty. The legacy behavior
9665 // is no-op. Remove to refer to mNetworkActive only.
9666 if (mNetworkActive || mActiveIdleTimers.isEmpty()) {
9667 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REPORT_NETWORK_ACTIVITY));
9668 }
9669 }
9670 }
9671
9672 // The network activity should only be updated from ConnectivityService handler thread
9673 // when mActiveIdleTimers lock is held.
9674 @GuardedBy("mActiveIdleTimers")
9675 private void reportNetworkActive() {
9676 final int length = mNetworkActivityListeners.beginBroadcast();
9677 if (DDBG) log("reportNetworkActive, notify " + length + " listeners");
9678 try {
9679 for (int i = 0; i < length; i++) {
9680 try {
9681 mNetworkActivityListeners.getBroadcastItem(i).onNetworkActive();
9682 } catch (RemoteException | RuntimeException e) {
9683 loge("Fail to send network activie to listener " + e);
9684 }
9685 }
9686 } finally {
9687 mNetworkActivityListeners.finishBroadcast();
9688 }
9689 }
9690
9691 @GuardedBy("mActiveIdleTimers")
9692 public void handleReportNetworkActivity() {
9693 synchronized (mActiveIdleTimers) {
9694 reportNetworkActive();
9695 }
9696 }
9697
9698 // This is deprecated and only to support legacy use cases.
9699 private int transportTypeToLegacyType(int type) {
9700 switch (type) {
9701 case NetworkCapabilities.TRANSPORT_CELLULAR:
9702 return TYPE_MOBILE;
9703 case NetworkCapabilities.TRANSPORT_WIFI:
9704 return TYPE_WIFI;
9705 case NetworkCapabilities.TRANSPORT_BLUETOOTH:
9706 return TYPE_BLUETOOTH;
9707 case NetworkCapabilities.TRANSPORT_ETHERNET:
9708 return TYPE_ETHERNET;
9709 default:
9710 loge("Unexpected transport in transportTypeToLegacyType: " + type);
9711 }
9712 return ConnectivityManager.TYPE_NONE;
9713 }
9714
9715 public void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
9716 final Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
9717 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
9718 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
9719 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
9720 final long ident = Binder.clearCallingIdentity();
9721 try {
9722 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
9723 RECEIVE_DATA_ACTIVITY_CHANGE,
9724 null /* resultReceiver */,
9725 null /* scheduler */,
9726 0 /* initialCode */,
9727 null /* initialData */,
9728 null /* initialExtra */);
9729 } finally {
9730 Binder.restoreCallingIdentity(ident);
9731 }
9732 }
9733
9734 /**
9735 * Setup data activity tracking for the given network.
9736 *
9737 * Every {@code setupDataActivityTracking} should be paired with a
9738 * {@link #removeDataActivityTracking} for cleanup.
9739 */
9740 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
9741 final String iface = networkAgent.linkProperties.getInterfaceName();
9742
9743 final int timeout;
9744 final int type;
9745
9746 if (networkAgent.networkCapabilities.hasTransport(
9747 NetworkCapabilities.TRANSPORT_CELLULAR)) {
9748 timeout = Settings.Global.getInt(mContext.getContentResolver(),
9749 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_MOBILE,
9750 10);
9751 type = NetworkCapabilities.TRANSPORT_CELLULAR;
9752 } else if (networkAgent.networkCapabilities.hasTransport(
9753 NetworkCapabilities.TRANSPORT_WIFI)) {
9754 timeout = Settings.Global.getInt(mContext.getContentResolver(),
9755 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_WIFI,
9756 15);
9757 type = NetworkCapabilities.TRANSPORT_WIFI;
9758 } else {
9759 return; // do not track any other networks
9760 }
9761
9762 updateRadioPowerState(true /* isActive */, type);
9763
9764 if (timeout > 0 && iface != null) {
9765 try {
9766 synchronized (mActiveIdleTimers) {
9767 // Networks start up.
9768 mNetworkActive = true;
9769 mActiveIdleTimers.put(iface, new IdleTimerParams(timeout, type));
9770 mNetd.idletimerAddInterface(iface, timeout, Integer.toString(type));
9771 reportNetworkActive();
9772 }
9773 } catch (Exception e) {
9774 // You shall not crash!
9775 loge("Exception in setupDataActivityTracking " + e);
9776 }
9777 }
9778 }
9779
9780 /**
9781 * Remove data activity tracking when network disconnects.
9782 */
9783 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
9784 final String iface = networkAgent.linkProperties.getInterfaceName();
9785 final NetworkCapabilities caps = networkAgent.networkCapabilities;
9786
9787 if (iface == null) return;
9788
9789 final int type;
9790 if (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
9791 type = NetworkCapabilities.TRANSPORT_CELLULAR;
9792 } else if (caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
9793 type = NetworkCapabilities.TRANSPORT_WIFI;
9794 } else {
9795 return; // do not track any other networks
9796 }
9797
9798 try {
9799 updateRadioPowerState(false /* isActive */, type);
9800 synchronized (mActiveIdleTimers) {
9801 final IdleTimerParams params = mActiveIdleTimers.remove(iface);
9802 // The call fails silently if no idle timer setup for this interface
9803 mNetd.idletimerRemoveInterface(iface, params.timeout,
9804 Integer.toString(params.transportType));
9805 }
9806 } catch (Exception e) {
9807 // You shall not crash!
9808 loge("Exception in removeDataActivityTracking " + e);
9809 }
9810 }
9811
9812 /**
9813 * Update data activity tracking when network state is updated.
9814 */
9815 public void updateDataActivityTracking(NetworkAgentInfo newNetwork,
9816 NetworkAgentInfo oldNetwork) {
9817 if (newNetwork != null) {
9818 setupDataActivityTracking(newNetwork);
9819 }
9820 if (oldNetwork != null) {
9821 removeDataActivityTracking(oldNetwork);
9822 }
9823 }
9824
9825 private void updateRadioPowerState(boolean isActive, int transportType) {
9826 final BatteryStatsManager bs = mContext.getSystemService(BatteryStatsManager.class);
9827 switch (transportType) {
9828 case NetworkCapabilities.TRANSPORT_CELLULAR:
9829 bs.reportMobileRadioPowerState(isActive, NO_UID);
9830 break;
9831 case NetworkCapabilities.TRANSPORT_WIFI:
9832 bs.reportWifiRadioPowerState(isActive, NO_UID);
9833 break;
9834 default:
9835 logw("Untracked transport type:" + transportType);
9836 }
9837 }
9838
9839 public boolean isDefaultNetworkActive() {
9840 synchronized (mActiveIdleTimers) {
9841 // If there are no idle timers, it means that system is not monitoring activity,
9842 // so the default network is always considered active.
9843 //
9844 // TODO : Distinguish between the cases where mActiveIdleTimers is empty because
9845 // tracking is disabled (negative idle timer value configured), or no active default
9846 // network. In the latter case, this reports active but it should report inactive.
9847 return mNetworkActive || mActiveIdleTimers.isEmpty();
9848 }
9849 }
9850
9851 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
9852 mNetworkActivityListeners.register(l);
9853 }
9854
9855 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
9856 mNetworkActivityListeners.unregister(l);
9857 }
9858
9859 public void dump(IndentingPrintWriter pw) {
9860 synchronized (mActiveIdleTimers) {
9861 pw.print("mNetworkActive="); pw.println(mNetworkActive);
9862 pw.println("Idle timers:");
9863 for (HashMap.Entry<String, IdleTimerParams> ent : mActiveIdleTimers.entrySet()) {
9864 pw.print(" "); pw.print(ent.getKey()); pw.println(":");
9865 final IdleTimerParams params = ent.getValue();
9866 pw.print(" timeout="); pw.print(params.timeout);
9867 pw.print(" type="); pw.println(params.transportType);
9868 }
9869 }
9870 }
9871 }
9872
9873 /**
9874 * Registers {@link QosSocketFilter} with {@link IQosCallback}.
9875 *
9876 * @param socketInfo the socket information
9877 * @param callback the callback to register
9878 */
9879 @Override
9880 public void registerQosSocketCallback(@NonNull final QosSocketInfo socketInfo,
9881 @NonNull final IQosCallback callback) {
9882 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(socketInfo.getNetwork());
9883 if (nai == null || nai.networkCapabilities == null) {
9884 try {
9885 callback.onError(QosCallbackException.EX_TYPE_FILTER_NETWORK_RELEASED);
9886 } catch (final RemoteException ex) {
9887 loge("registerQosCallbackInternal: RemoteException", ex);
9888 }
9889 return;
9890 }
9891 registerQosCallbackInternal(new QosSocketFilter(socketInfo), callback, nai);
9892 }
9893
9894 /**
9895 * Register a {@link IQosCallback} with base {@link QosFilter}.
9896 *
9897 * @param filter the filter to register
9898 * @param callback the callback to register
9899 * @param nai the agent information related to the filter's network
9900 */
9901 @VisibleForTesting
9902 public void registerQosCallbackInternal(@NonNull final QosFilter filter,
9903 @NonNull final IQosCallback callback, @NonNull final NetworkAgentInfo nai) {
9904 if (filter == null) throw new IllegalArgumentException("filter must be non-null");
9905 if (callback == null) throw new IllegalArgumentException("callback must be non-null");
9906
9907 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
9908 enforceConnectivityRestrictedNetworksPermission();
9909 }
9910 mQosCallbackTracker.registerCallback(callback, filter, nai);
9911 }
9912
9913 /**
9914 * Unregisters the given callback.
9915 *
9916 * @param callback the callback to unregister
9917 */
9918 @Override
9919 public void unregisterQosCallback(@NonNull final IQosCallback callback) {
9920 Objects.requireNonNull(callback, "callback must be non-null");
9921 mQosCallbackTracker.unregisterCallback(callback);
9922 }
9923
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00009924 /**
9925 * Request that a user profile is put by default on a network matching a given preference.
9926 *
9927 * See the documentation for the individual preferences for a description of the supported
9928 * behaviors.
9929 *
9930 * @param profile the profile concerned.
9931 * @param preference the preference for this profile, as one of the PROFILE_NETWORK_PREFERENCE_*
9932 * constants.
9933 * @param listener an optional listener to listen for completion of the operation.
9934 */
9935 @Override
9936 public void setProfileNetworkPreference(@NonNull final UserHandle profile,
9937 @ConnectivityManager.ProfileNetworkPreference final int preference,
9938 @Nullable final IOnCompleteListener listener) {
9939 Objects.requireNonNull(profile);
9940 PermissionUtils.enforceNetworkStackPermission(mContext);
9941 if (DBG) {
9942 log("setProfileNetworkPreference " + profile + " to " + preference);
9943 }
9944 if (profile.getIdentifier() < 0) {
9945 throw new IllegalArgumentException("Must explicitly specify a user handle ("
9946 + "UserHandle.CURRENT not supported)");
9947 }
9948 final UserManager um = mContext.getSystemService(UserManager.class);
9949 if (!um.isManagedProfile(profile.getIdentifier())) {
9950 throw new IllegalArgumentException("Profile must be a managed profile");
9951 }
paulhude5efb92021-05-26 21:56:03 +08009952
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00009953 final NetworkCapabilities nc;
9954 switch (preference) {
9955 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT:
9956 nc = null;
9957 break;
9958 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE:
9959 final UidRange uids = UidRange.createForUser(profile);
9960 nc = createDefaultNetworkCapabilitiesForUidRange(uids);
9961 nc.addCapability(NET_CAPABILITY_ENTERPRISE);
9962 nc.removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
9963 break;
9964 default:
9965 throw new IllegalArgumentException(
9966 "Invalid preference in setProfileNetworkPreference");
9967 }
9968 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_PROFILE_NETWORK_PREFERENCE,
9969 new Pair<>(new ProfileNetworkPreferences.Preference(profile, nc), listener)));
9970 }
9971
9972 private void validateNetworkCapabilitiesOfProfileNetworkPreference(
9973 @Nullable final NetworkCapabilities nc) {
9974 if (null == nc) return; // Null caps are always allowed. It means to remove the setting.
9975 ensureRequestableCapabilities(nc);
9976 }
9977
9978 private ArraySet<NetworkRequestInfo> createNrisFromProfileNetworkPreferences(
9979 @NonNull final ProfileNetworkPreferences prefs) {
9980 final ArraySet<NetworkRequestInfo> result = new ArraySet<>();
9981 for (final ProfileNetworkPreferences.Preference pref : prefs.preferences) {
9982 // The NRI for a user should be comprised of two layers:
9983 // - The request for the capabilities
9984 // - The request for the default network, for fallback. Create an image of it to
9985 // have the correct UIDs in it (also a request can only be part of one NRI, because
9986 // of lookups in 1:1 associations like mNetworkRequests).
9987 // Note that denying a fallback can be implemented simply by not adding the second
9988 // request.
9989 final ArrayList<NetworkRequest> nrs = new ArrayList<>();
9990 nrs.add(createNetworkRequest(NetworkRequest.Type.REQUEST, pref.capabilities));
9991 nrs.add(createDefaultInternetRequestForTransport(
9992 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
9993 setNetworkRequestUids(nrs, UidRange.fromIntRanges(pref.capabilities.getUids()));
paulhuc2198772021-05-26 15:19:20 +08009994 final NetworkRequestInfo nri = new NetworkRequestInfo(Process.myUid(), nrs,
paulhu48291862021-07-14 14:53:57 +08009995 PREFERENCE_ORDER_PROFILE);
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00009996 result.add(nri);
9997 }
9998 return result;
9999 }
10000
10001 private void handleSetProfileNetworkPreference(
10002 @NonNull final ProfileNetworkPreferences.Preference preference,
10003 @Nullable final IOnCompleteListener listener) {
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +000010004 validateNetworkCapabilitiesOfProfileNetworkPreference(preference.capabilities);
10005
10006 mProfileNetworkPreferences = mProfileNetworkPreferences.plus(preference);
10007 mSystemNetworkRequestCounter.transact(
10008 mDeps.getCallingUid(), mProfileNetworkPreferences.preferences.size(),
10009 () -> {
10010 final ArraySet<NetworkRequestInfo> nris =
10011 createNrisFromProfileNetworkPreferences(mProfileNetworkPreferences);
paulhu48291862021-07-14 14:53:57 +080010012 replaceDefaultNetworkRequestsForPreference(nris, PREFERENCE_ORDER_PROFILE);
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +000010013 });
10014 // Finally, rematch.
10015 rematchAllNetworksAndRequests();
10016
10017 if (null != listener) {
10018 try {
10019 listener.onComplete();
10020 } catch (RemoteException e) {
10021 loge("Listener for setProfileNetworkPreference has died");
10022 }
10023 }
10024 }
10025
paulhu71ad4f12021-05-25 14:56:27 +080010026 @VisibleForTesting
10027 @NonNull
10028 ArraySet<NetworkRequestInfo> createNrisFromMobileDataPreferredUids(
10029 @NonNull final Set<Integer> uids) {
10030 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
10031 if (uids.size() == 0) {
10032 // Should not create NetworkRequestInfo if no preferences. Without uid range in
10033 // NetworkRequestInfo, makeDefaultForApps() would treat it as a illegal NRI.
10034 if (DBG) log("Don't create NetworkRequestInfo because no preferences");
10035 return nris;
10036 }
10037
10038 final List<NetworkRequest> requests = new ArrayList<>();
10039 // The NRI should be comprised of two layers:
10040 // - The request for the mobile network preferred.
10041 // - The request for the default network, for fallback.
10042 requests.add(createDefaultInternetRequestForTransport(
Ansik605e7702021-06-29 19:06:37 +090010043 TRANSPORT_CELLULAR, NetworkRequest.Type.REQUEST));
paulhu71ad4f12021-05-25 14:56:27 +080010044 requests.add(createDefaultInternetRequestForTransport(
10045 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
10046 final Set<UidRange> ranges = new ArraySet<>();
10047 for (final int uid : uids) {
10048 ranges.add(new UidRange(uid, uid));
10049 }
10050 setNetworkRequestUids(requests, ranges);
paulhuc2198772021-05-26 15:19:20 +080010051 nris.add(new NetworkRequestInfo(Process.myUid(), requests,
paulhu48291862021-07-14 14:53:57 +080010052 PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED));
paulhu71ad4f12021-05-25 14:56:27 +080010053 return nris;
10054 }
10055
10056 private void handleMobileDataPreferredUidsChanged() {
paulhu71ad4f12021-05-25 14:56:27 +080010057 mMobileDataPreferredUids = ConnectivitySettingsManager.getMobileDataPreferredUids(mContext);
10058 mSystemNetworkRequestCounter.transact(
10059 mDeps.getCallingUid(), 1 /* numOfNewRequests */,
10060 () -> {
10061 final ArraySet<NetworkRequestInfo> nris =
10062 createNrisFromMobileDataPreferredUids(mMobileDataPreferredUids);
paulhude5efb92021-05-26 21:56:03 +080010063 replaceDefaultNetworkRequestsForPreference(nris,
paulhu48291862021-07-14 14:53:57 +080010064 PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED);
paulhu71ad4f12021-05-25 14:56:27 +080010065 });
10066 // Finally, rematch.
10067 rematchAllNetworksAndRequests();
10068 }
10069
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +000010070 private void enforceAutomotiveDevice() {
10071 final boolean isAutomotiveDevice =
10072 mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE);
10073 if (!isAutomotiveDevice) {
10074 throw new UnsupportedOperationException(
10075 "setOemNetworkPreference() is only available on automotive devices.");
10076 }
10077 }
10078
10079 /**
10080 * Used by automotive devices to set the network preferences used to direct traffic at an
10081 * application level as per the given OemNetworkPreferences. An example use-case would be an
10082 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
10083 * vehicle via a particular network.
10084 *
10085 * Calling this will overwrite the existing preference.
10086 *
10087 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
10088 * @param listener {@link ConnectivityManager.OnCompleteListener} Listener used
10089 * to communicate completion of setOemNetworkPreference();
10090 */
10091 @Override
10092 public void setOemNetworkPreference(
10093 @NonNull final OemNetworkPreferences preference,
10094 @Nullable final IOnCompleteListener listener) {
10095
James Mattisfa270db2021-05-31 17:11:10 -070010096 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
10097 // Only bypass the permission/device checks if this is a valid test request.
10098 if (isValidTestOemNetworkPreference(preference)) {
10099 enforceManageTestNetworksPermission();
10100 } else {
10101 enforceAutomotiveDevice();
10102 enforceOemNetworkPreferencesPermission();
10103 validateOemNetworkPreferences(preference);
10104 }
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +000010105
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +000010106 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_OEM_NETWORK_PREFERENCE,
10107 new Pair<>(preference, listener)));
10108 }
10109
James Mattisfa270db2021-05-31 17:11:10 -070010110 /**
10111 * Check the validity of an OEM network preference to be used for testing purposes.
10112 * @param preference the preference to validate
10113 * @return true if this is a valid OEM network preference test request.
10114 */
10115 private boolean isValidTestOemNetworkPreference(
10116 @NonNull final OemNetworkPreferences preference) {
10117 // Allow for clearing of an existing OemNetworkPreference used for testing.
10118 // This isn't called on the handler thread so it is possible that mOemNetworkPreferences
10119 // changes after this check is complete. This is an unlikely scenario as calling of this API
10120 // is controlled by the OEM therefore the added complexity is not worth adding given those
10121 // circumstances. That said, it is an edge case to be aware of hence this comment.
10122 final boolean isValidTestClearPref = preference.getNetworkPreferences().size() == 0
10123 && isTestOemNetworkPreference(mOemNetworkPreferences);
10124 return isTestOemNetworkPreference(preference) || isValidTestClearPref;
10125 }
10126
10127 private boolean isTestOemNetworkPreference(@NonNull final OemNetworkPreferences preference) {
10128 final Map<String, Integer> prefMap = preference.getNetworkPreferences();
10129 return prefMap.size() == 1
10130 && (prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST)
10131 || prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST_ONLY));
10132 }
10133
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +000010134 private void validateOemNetworkPreferences(@NonNull OemNetworkPreferences preference) {
10135 for (@OemNetworkPreferences.OemNetworkPreference final int pref
10136 : preference.getNetworkPreferences().values()) {
James Mattisfa270db2021-05-31 17:11:10 -070010137 if (pref <= 0 || OemNetworkPreferences.OEM_NETWORK_PREFERENCE_MAX < pref) {
10138 throw new IllegalArgumentException(
10139 OemNetworkPreferences.oemNetworkPreferenceToString(pref)
10140 + " is an invalid value.");
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +000010141 }
10142 }
10143 }
10144
10145 private void handleSetOemNetworkPreference(
10146 @NonNull final OemNetworkPreferences preference,
10147 @Nullable final IOnCompleteListener listener) {
10148 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
10149 if (DBG) {
10150 log("set OEM network preferences :" + preference.toString());
10151 }
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +000010152
10153 mOemNetworkPreferencesLogs.log("UPDATE INITIATED: " + preference);
10154 final int uniquePreferenceCount = new ArraySet<>(
10155 preference.getNetworkPreferences().values()).size();
10156 mSystemNetworkRequestCounter.transact(
10157 mDeps.getCallingUid(), uniquePreferenceCount,
10158 () -> {
10159 final ArraySet<NetworkRequestInfo> nris =
10160 new OemNetworkRequestFactory()
10161 .createNrisFromOemNetworkPreferences(preference);
paulhu48291862021-07-14 14:53:57 +080010162 replaceDefaultNetworkRequestsForPreference(nris, PREFERENCE_ORDER_OEM);
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +000010163 });
10164 mOemNetworkPreferences = preference;
10165
10166 if (null != listener) {
10167 try {
10168 listener.onComplete();
10169 } catch (RemoteException e) {
10170 loge("Can't send onComplete in handleSetOemNetworkPreference", e);
10171 }
10172 }
10173 }
10174
10175 private void replaceDefaultNetworkRequestsForPreference(
paulhu48291862021-07-14 14:53:57 +080010176 @NonNull final Set<NetworkRequestInfo> nris, final int preferenceOrder) {
paulhude5efb92021-05-26 21:56:03 +080010177 // Skip the requests which are set by other network preference. Because the uid range rules
10178 // should stay in netd.
10179 final Set<NetworkRequestInfo> requests = new ArraySet<>(mDefaultNetworkRequests);
paulhu48291862021-07-14 14:53:57 +080010180 requests.removeIf(request -> request.mPreferenceOrder != preferenceOrder);
paulhude5efb92021-05-26 21:56:03 +080010181 handleRemoveNetworkRequests(requests);
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +000010182 addPerAppDefaultNetworkRequests(nris);
10183 }
10184
10185 private void addPerAppDefaultNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
10186 ensureRunningOnConnectivityServiceThread();
10187 mDefaultNetworkRequests.addAll(nris);
10188 final ArraySet<NetworkRequestInfo> perAppCallbackRequestsToUpdate =
10189 getPerAppCallbackRequestsToUpdate();
10190 final ArraySet<NetworkRequestInfo> nrisToRegister = new ArraySet<>(nris);
10191 mSystemNetworkRequestCounter.transact(
10192 mDeps.getCallingUid(), perAppCallbackRequestsToUpdate.size(),
10193 () -> {
10194 nrisToRegister.addAll(
10195 createPerAppCallbackRequestsToRegister(perAppCallbackRequestsToUpdate));
10196 handleRemoveNetworkRequests(perAppCallbackRequestsToUpdate);
10197 handleRegisterNetworkRequests(nrisToRegister);
10198 });
10199 }
10200
10201 /**
10202 * All current requests that are tracking the default network need to be assessed as to whether
10203 * or not the current set of per-application default requests will be changing their default
10204 * network. If so, those requests will need to be updated so that they will send callbacks for
10205 * default network changes at the appropriate time. Additionally, those requests tracking the
10206 * default that were previously updated by this flow will need to be reassessed.
10207 * @return the nris which will need to be updated.
10208 */
10209 private ArraySet<NetworkRequestInfo> getPerAppCallbackRequestsToUpdate() {
10210 final ArraySet<NetworkRequestInfo> defaultCallbackRequests = new ArraySet<>();
10211 // Get the distinct nris to check since for multilayer requests, it is possible to have the
10212 // same nri in the map's values for each of its NetworkRequest objects.
10213 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>(mNetworkRequests.values());
10214 for (final NetworkRequestInfo nri : nris) {
10215 // Include this nri if it is currently being tracked.
10216 if (isPerAppTrackedNri(nri)) {
10217 defaultCallbackRequests.add(nri);
10218 continue;
10219 }
10220 // We only track callbacks for requests tracking the default.
10221 if (NetworkRequest.Type.TRACK_DEFAULT != nri.mRequests.get(0).type) {
10222 continue;
10223 }
10224 // Include this nri if it will be tracked by the new per-app default requests.
10225 final boolean isNriGoingToBeTracked =
10226 getDefaultRequestTrackingUid(nri.mAsUid) != mDefaultRequest;
10227 if (isNriGoingToBeTracked) {
10228 defaultCallbackRequests.add(nri);
10229 }
10230 }
10231 return defaultCallbackRequests;
10232 }
10233
10234 /**
10235 * Create nris for those network requests that are currently tracking the default network that
10236 * are being controlled by a per-application default.
10237 * @param perAppCallbackRequestsForUpdate the baseline network requests to be used as the
10238 * foundation when creating the nri. Important items include the calling uid's original
10239 * NetworkRequest to be used when mapping callbacks as well as the caller's uid and name. These
10240 * requests are assumed to have already been validated as needing to be updated.
10241 * @return the Set of nris to use when registering network requests.
10242 */
10243 private ArraySet<NetworkRequestInfo> createPerAppCallbackRequestsToRegister(
10244 @NonNull final ArraySet<NetworkRequestInfo> perAppCallbackRequestsForUpdate) {
10245 final ArraySet<NetworkRequestInfo> callbackRequestsToRegister = new ArraySet<>();
10246 for (final NetworkRequestInfo callbackRequest : perAppCallbackRequestsForUpdate) {
10247 final NetworkRequestInfo trackingNri =
10248 getDefaultRequestTrackingUid(callbackRequest.mAsUid);
10249
10250 // If this nri is not being tracked, the change it back to an untracked nri.
10251 if (trackingNri == mDefaultRequest) {
10252 callbackRequestsToRegister.add(new NetworkRequestInfo(
10253 callbackRequest,
10254 Collections.singletonList(callbackRequest.getNetworkRequestForCallback())));
10255 continue;
10256 }
10257
10258 final NetworkRequest request = callbackRequest.mRequests.get(0);
10259 callbackRequestsToRegister.add(new NetworkRequestInfo(
10260 callbackRequest,
10261 copyNetworkRequestsForUid(
10262 trackingNri.mRequests, callbackRequest.mAsUid,
10263 callbackRequest.mUid, request.getRequestorPackageName())));
10264 }
10265 return callbackRequestsToRegister;
10266 }
10267
10268 private static void setNetworkRequestUids(@NonNull final List<NetworkRequest> requests,
10269 @NonNull final Set<UidRange> uids) {
10270 for (final NetworkRequest req : requests) {
10271 req.networkCapabilities.setUids(UidRange.toIntRanges(uids));
10272 }
10273 }
10274
10275 /**
10276 * Class used to generate {@link NetworkRequestInfo} based off of {@link OemNetworkPreferences}.
10277 */
10278 @VisibleForTesting
10279 final class OemNetworkRequestFactory {
10280 ArraySet<NetworkRequestInfo> createNrisFromOemNetworkPreferences(
10281 @NonNull final OemNetworkPreferences preference) {
10282 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
10283 final SparseArray<Set<Integer>> uids =
10284 createUidsFromOemNetworkPreferences(preference);
10285 for (int i = 0; i < uids.size(); i++) {
10286 final int key = uids.keyAt(i);
10287 final Set<Integer> value = uids.valueAt(i);
10288 final NetworkRequestInfo nri = createNriFromOemNetworkPreferences(key, value);
10289 // No need to add an nri without any requests.
10290 if (0 == nri.mRequests.size()) {
10291 continue;
10292 }
10293 nris.add(nri);
10294 }
10295
10296 return nris;
10297 }
10298
10299 private SparseArray<Set<Integer>> createUidsFromOemNetworkPreferences(
10300 @NonNull final OemNetworkPreferences preference) {
James Mattisb6b6a432021-06-01 22:30:36 -070010301 final SparseArray<Set<Integer>> prefToUids = new SparseArray<>();
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +000010302 final PackageManager pm = mContext.getPackageManager();
10303 final List<UserHandle> users =
10304 mContext.getSystemService(UserManager.class).getUserHandles(true);
10305 if (null == users || users.size() == 0) {
10306 if (VDBG || DDBG) {
10307 log("No users currently available for setting the OEM network preference.");
10308 }
James Mattisb6b6a432021-06-01 22:30:36 -070010309 return prefToUids;
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +000010310 }
10311 for (final Map.Entry<String, Integer> entry :
10312 preference.getNetworkPreferences().entrySet()) {
10313 @OemNetworkPreferences.OemNetworkPreference final int pref = entry.getValue();
James Mattisb6b6a432021-06-01 22:30:36 -070010314 // Add the rules for all users as this policy is device wide.
10315 for (final UserHandle user : users) {
10316 try {
10317 final int uid = pm.getApplicationInfoAsUser(entry.getKey(), 0, user).uid;
10318 if (!prefToUids.contains(pref)) {
10319 prefToUids.put(pref, new ArraySet<>());
10320 }
10321 prefToUids.get(pref).add(uid);
10322 } catch (PackageManager.NameNotFoundException e) {
10323 // Although this may seem like an error scenario, it is ok that uninstalled
10324 // packages are sent on a network preference as the system will watch for
10325 // package installations associated with this network preference and update
10326 // accordingly. This is done to minimize race conditions on app install.
10327 continue;
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +000010328 }
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +000010329 }
10330 }
James Mattisb6b6a432021-06-01 22:30:36 -070010331 return prefToUids;
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +000010332 }
10333
10334 private NetworkRequestInfo createNriFromOemNetworkPreferences(
10335 @OemNetworkPreferences.OemNetworkPreference final int preference,
10336 @NonNull final Set<Integer> uids) {
10337 final List<NetworkRequest> requests = new ArrayList<>();
10338 // Requests will ultimately be evaluated by order of insertion therefore it matters.
10339 switch (preference) {
10340 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID:
10341 requests.add(createUnmeteredNetworkRequest());
10342 requests.add(createOemPaidNetworkRequest());
10343 requests.add(createDefaultInternetRequestForTransport(
10344 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
10345 break;
10346 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_NO_FALLBACK:
10347 requests.add(createUnmeteredNetworkRequest());
10348 requests.add(createOemPaidNetworkRequest());
10349 break;
10350 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_ONLY:
10351 requests.add(createOemPaidNetworkRequest());
10352 break;
10353 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PRIVATE_ONLY:
10354 requests.add(createOemPrivateNetworkRequest());
10355 break;
James Mattisfa270db2021-05-31 17:11:10 -070010356 case OEM_NETWORK_PREFERENCE_TEST:
10357 requests.add(createUnmeteredNetworkRequest());
10358 requests.add(createTestNetworkRequest());
10359 requests.add(createDefaultRequest());
10360 break;
10361 case OEM_NETWORK_PREFERENCE_TEST_ONLY:
10362 requests.add(createTestNetworkRequest());
10363 break;
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +000010364 default:
10365 // This should never happen.
10366 throw new IllegalArgumentException("createNriFromOemNetworkPreferences()"
10367 + " called with invalid preference of " + preference);
10368 }
10369
James Mattisfa270db2021-05-31 17:11:10 -070010370 final ArraySet<UidRange> ranges = new ArraySet<>();
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +000010371 for (final int uid : uids) {
10372 ranges.add(new UidRange(uid, uid));
10373 }
10374 setNetworkRequestUids(requests, ranges);
paulhu48291862021-07-14 14:53:57 +080010375 return new NetworkRequestInfo(Process.myUid(), requests, PREFERENCE_ORDER_OEM);
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +000010376 }
10377
10378 private NetworkRequest createUnmeteredNetworkRequest() {
10379 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
10380 .addCapability(NET_CAPABILITY_NOT_METERED)
10381 .addCapability(NET_CAPABILITY_VALIDATED);
10382 return createNetworkRequest(NetworkRequest.Type.LISTEN, netcap);
10383 }
10384
10385 private NetworkRequest createOemPaidNetworkRequest() {
10386 // NET_CAPABILITY_OEM_PAID is a restricted capability.
10387 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
10388 .addCapability(NET_CAPABILITY_OEM_PAID)
10389 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
10390 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
10391 }
10392
10393 private NetworkRequest createOemPrivateNetworkRequest() {
10394 // NET_CAPABILITY_OEM_PRIVATE is a restricted capability.
10395 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
10396 .addCapability(NET_CAPABILITY_OEM_PRIVATE)
10397 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
10398 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
10399 }
10400
10401 private NetworkCapabilities createDefaultPerAppNetCap() {
James Mattisfa270db2021-05-31 17:11:10 -070010402 final NetworkCapabilities netcap = new NetworkCapabilities();
10403 netcap.addCapability(NET_CAPABILITY_INTERNET);
10404 netcap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
10405 return netcap;
10406 }
10407
10408 private NetworkRequest createTestNetworkRequest() {
10409 final NetworkCapabilities netcap = new NetworkCapabilities();
10410 netcap.clearAll();
10411 netcap.addTransportType(TRANSPORT_TEST);
10412 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +000010413 }
10414 }
10415}