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