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